Skip to main content

Full text of "INEW2338 - Advanced Java Programming"

See other formats


1. Preface 


1. 


Java4510: Preface to INEW 2338 


2. Network Programming 


. Java4610-Preface 

. Java4620: General Information 

. Java4620r-Review 

. Java4630: The InetAddress Class 

. Java4630r-Review 

. Java4640: The URL Class and the URLEncoder Class 
. Java4640r-Review 

. Java4650: The URLConnection Class 

. Java4650r-Review 

10. 
11. 
12. 


Java4655: A Rendering Web Browser 
Java4660: Sockets 
Java4660r-Review 


3. Search Engines 


1. 
2: 


Java4585: Getting Started with Search Engines 
Java4590r-Review for search engines 


4. Servlets 


1 


OOOAN DU BW N 


— 


— 
—_ 


. Java4530: Getting Started with Servlets 

. Java4530r-Review 

. Java4535: Introduction to Servlet Code 

. Java4535r-Review 

. Java4550: Session Tracking using Hidden Fields 

. Java4550r-Review 

. Java4560: Session Tracking using URL Rewriting 

. Java4570: Session Tracking using Cookies 

. Java4570r-Review 

. Java4580: Session Tracking using the Session Tracking 


API 


. Java4580r-Review 


5. JSON 


a 
POoOoWOON aU BRWN RP 


—_— 
& WW 


. Json0195: Preface to JSON 

. Json0200: The What and Why of JSON 

. Json0200R: Review 

. Json0205: Getting Started 

. Json0205R: Review 

. Json0210: Structure of the json-simple Java Library 
. Json0210R: Review 

. Json0215: Encoding JSON Strings 

. Json0215R: Review 

. Json0220: Decoding JSON Strings 

. Json0220R: Review 

12. 
. Json0225R: Review 

. Json0230: Decoding JSON Arrays 
15. 


Json0225: Encoding JSON Arrays 


Json0O230R: Review 


6. Frameworks 


1, 


Java4710: INEW 2338 - Java EE 7 and Frameworks 


Java4510: Preface to INEW 2338 
This is a preface to the INEW2338 material. 


Revised: Thu Jun 02 14:40:19 CDT 2016 
This page is included in the following Books: 


e INEW2338 - Advanced Java Programming 
¢ Object-Oriented Programming_(QOP) with Java 


Table of Contents 


e Welcome 

e Programming Oldies but Goodies 
¢ Downloads 

e Miscellaneous 


Welcome 


Welcome to the course material for INEW2338 - Advanced Java 
Programming , which I teach at Austin Community College in Austin, TX. 


Information about the course 
The college website for this course is: http://www.austincc.edu/baldwin/ 


The prerequisite for the course is ITSE2317 - Java Programming 
(Intermediate) or department approval. 


Each semester, the course covers three major topics : 


e Network Programming 
e Search Engines OR Servlets OR JSON 
e Java EE and Frameworks 


Note: 


Note: Although only one of the topics Search Engines , Servlets , or JSON 
is covered in the course in any particular semester, all three are important. 
The course material in the Blackboard course management program will 
indicate which topic is covered in the current semester. 

Students are encouraged to study all three topics for their own educational 
purposes in order to enhance their prospects of landing a job as a Java 
programmer. 


Programming Oldies but Goodies 


While much of the material required to succeed in this course is contained 
in the modules in this book, a large amount of relevant material is also 
contained in the collection titled Programming Oldies But Goodies , which 
is a work in process. The material in that collection has not yet been 
converted to the cnxml format required by OpenStax. Instead, the material 
in that collection is still in its original html format. 


You would do well to familiarize yourself with that material as well. 


Downloads 


I encourage you to take advantage of the download options that OpenStax 
has to offer in order to customize this material for use in your organized 
courses or for personal self study. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4510: Preface to INEW 2338 
e File: Java4510.htm 


e Published: 12/17/13 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from OpenStax, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on OpenStax and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4610-Preface 
This module serves as the preface to a sub-collection of modules on 
network programming. 


Table of Contents 
e Discussion 


e What's next? 
e Miscellaneous 


Discussion 


This module serves as the preface to a sub-collection of modules on 
network programming. The modules in this sub-collection are designed for 
teaching INEW 2338 Advanced Java (Web) at Austin Community 
College in Austin, TX. 


What's next? 
The next module is titled Java4620: General Information . 


As you might surmise from the title, it deals with such topics as 
communication protocols, clients, servers, IP, TCP, ports, etc. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4610-Preface 
e File: Java4610.htm 

Published: 03/02/14 

Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4620: General Information 
The purpose of this module is to introduce the student to various aspects of 
network programming that will be incorporated into future modules. 


Table of Contents 


e Preface 
e Introduction 
e Background Information 


Communication Protocol 
Network Layers 

Clients and Servers 

IP, TCP, and, UDP 


o Oo 0 0 


IP_ Addresses 

Domain Names 

What is Your IP Address? 
Ports 

Firewalls 

Proxy Servers 

Standards and Protocols 
URL 


oOo 000 0 0 0 


e Socket Classes and the URL Class 


o Socket Programming 
o URL Programming 


e A local area network 
¢ The operating system 
e What's Next? 

e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
More specifically, it is one in a sub-collection of modules designed for 
teaching network programming in that course. The purpose of this module 
is to introduce the student to various aspects of network programming that 
will be incorporated into future modules. 


Introduction 


One of the Java books on my bookshelf makes the following analogy (or 
one very similar) . Just because you may know how to speak conversational 
French doesn't mean that you know how to interpret an autopsy report 
written in French. In order to interpret the autopsy report, you must also 
know a good deal about the meaning of the medical terms used in such 
reports. 


A similar situation exist for networking. It isn't very difficult to learn how 
to use the Java programming language to implement some network 
operations. However, in order to achieve depth in this area, you probably 
also need to know something about the many other technical aspects of 
networking. 


This is not a new field, and many good books have been written on the 
technical details of networking. you are referred to one or more of those 
books to gain an in-depth knowledge of networking. In particular, I would 
refer you to Java Network Programming by Elliotte Rusty Harold. 


In addition there are many other books that contain excellent sections on 
network programming. I would recommend that you take a look at the 
following: 


e Exploring Java by Patrick Niemeyer and Joshua Peck 
e Just Java 1.1 and Beyond by Peter van der Linden 

e Java Primer Plus by Tyma, Torok, and Downing 

e Java How to Program by Deitel and Deitel 


These books have been around for a long time, so you should be able to 
find a used copy online for a reasonable price. 


For the most part, this and the next few modules will be restricted to how 
you can use the programming capabilities of Java to write and execute 
network programs and won't attempt to go into overall network 
programming in depth. However, a minimal amount of background 
information will be required, so we will attempt to provide that background 
in this module. Subsequent modules will use this background along with the 
network programming capabilities of Java to write some simple, but 
interesting networking programs. 


Background Information 


For our purposes, a network is a group of computers and other devices that 
are connected in some fashion for the purpose of exchanging data. 


Each of the devices on the network can be thought of as a node , and each 
node has a unique address. The manner in which addresses are assigned will 
vary from one type of network to another, but in all cases, the address of 
each device must be unique so as to distinguish it from the other devices. 


Addresses are numeric quantities that are easy for computers to work with, 
but are not easy for humans to remember. Therefore, some networks also 
provide names that humans can more easily remember than numbers. 


Modern networks transfer data using a concept known as packet switching . 
This means that the data are encapsulated into packets that are transferred 
from the source to the destination. It is necessary to extract the data from 
one or more packets at the destination and use it to reconstruct the original 
message. 


Communication Protocol 


In order for two or more computers connected to a network to be able to 
exchange data in an orderly manner, they must adhere to a mutually 


acceptable communication protocol. The protocol defines the rules by 
which they communicate. 


Teaching your children to say please and thank you involves teaching them 
something about a protocol. If they occasionally forget to say please, 
however, they will probably get the cookie anyway. 


If a computer protocol requires the participating computers to say 
please, and they forget to say please, they probably won't get the 
cookie. 


There are many protocols available. For example, the HTTP protocol 
defines how web browsers and servers communicate and the SMTP 
protocol defines how email is transferred (we will write programs that 
implement part of the HTTP protocol) . 


Note here that I have been discussing application protocols that operate at 
the surface level. We will also be making mention of lower-level protocols 
that operate below the application level. Fortunately, as high-level Java 
programmers, we don't have to be too concerned about the lower-level 
protocols. We'll let the systems people worry about them. 


Network Layers 


Networks are logically separated into layers ranging from the Application 
Layer at the top to the Physical Layer at the bottom. The technical details of 
network layering are beyond the scope of this module. Fortunately, you will 
be able to write useful network programs using Java without understanding 
the details of network layering. 


The Application Layer is the layer that delivers data to the user. The layers 
below that are involved with getting data from the Application Layer at one 
end of the conversation to the Application Layer at the other end. For the 
most part, we will be concerned only with the Application Layer . 


Clients and Servers 


In these modules, we will be concerned with networked communications 
that involve client computers and a server computers. How do we know 
which is which? 


For the purposes of our studies, it will be sufficient to say that the 
client always initiates the conversation, and the server waits and 
listens for a client to initiate a conversation. 


IP, TCP, and UDP 
We need to know something about the following acronyms: 


e IP 
e TCP 
e UDP 


IP 


IP , which stands for Internet Protocol , is the protocol that will be involved 
below the Application Layer to move our data between a client and a server. 
Beyond knowing that it exists, we probably don't need to concern ourselves 
with the fact that IP is being used 


In fact, in some situations, some other protocol could be used to move our 
data between a client and a server. As long as it works, we really don't care 
too much. 


In a nutshell, IP is a network protocol that moves packets of data from a 
source to a destination. As the name implies, this is the protocol normally 
used on the Internet. 


TCP 


It is sometimes important to be able to have confidence that all packets that 
make up a message atrive at the destination undamaged and in proper order. 


The Transmission Control Protocol (‘TCP ) was added to IP to give each 
end of a connection the ability to acknowledge receipt of IP packets and to 
request retransmission of corrupted or lost packets. Also TCP makes it 
possible to put the packets back together at the destination in the same order 
that they were sent. 


Therefore, you will often hear people using both acronyms in the same 
breath, as in TCP/IP . The two work together to provide a reliable method 
of encapsulating a message into data packets, sending the packets to a 
destination, and reconstructing the message from the packets at the 
destination. 


UDP 


Sometimes it may not be critically important that all the packets arrive at 
the destination or that they arrive in the proper order. Further, sometimes, 
you may not want to incur the time delays and overhead cost associated 
with those guarantees. 


For example, if one computer is sending date and time information to 
another computer every 100 milliseconds, and the data in the packets is 
displayed on a digital clock as it is received, you might prefer that each 
packet make the trip as quickly as possible even if that means that 
occasionally a packet will be lost or damaged. 


The User Datagram Protocol ( UDP) is available to support this type of 
operation. UDP is often referred to as an unreliable protocol because there 
is no guarantee that a series of packets will arrive in the right order, or that 
they will arrive at all. 


As Java programmers, we have the choice of TCP or UDP, and we need to 
know enough about the characteristics of each to be able to make informed 


choices between them. 


IP Addresses 


We don't really need to know very much about IP to be able to use it, but 
we do need to know about the addressing scheme used in IP . 


Every computer attached to an IP network has a unique address, typically 
consisting of four bytes or 32 bits ( JPv4_) . 


Thirty-two bits are sufficient to define a large number of unique addresses, 
but the manner in which addresses are allocated is wasteful, and many of 
the addresses that have been allocated are not being used. 


Efforts are underway to expand the number of possible unique addresses to 
a much larger number. The planned number is the number of unique 
addresses that can be represented with a 128-bit address. The new scheme is 
known as [Pv6. 


For human consumption, we usually convert the value of each of the bytes 
to an unsigned decimal value and display them connected by periods to 
make them easier to remember. For example, as near as I can tell, as of this 
writing, the IP address of www.austincc.edu (the college where I teach) is 
206.77.150.222 . 


Domain Names 
What do I mean by www.austincc.edu ? 


Even though we can do some tricks to make the numeric IP addresses 
easier to remember, humans don't do a very good job of remembering long 
strings of numbers. Humans remember words and names better. Therefore, 
most IP addresses have a corresponding name known as a domain name . 
The domain name for the IP address 206.77.150.222 is www.austincc.edu . 


The Domain Name System (DNS) was developed to translate between IP 
addresses and domain names. Whenever you log your browser onto the 
internet and attempt to connect to a server using its domain name, the 
browser first communicates with a DNS server to learn the corresponding 
numeric IP address. The numeric IP address (and not the domain name) is 
encapsulated into the data packets and used by the internet protocol to route 
those packets from the source to the destination. 


(You should also be able to enter 206.77.150.222 into the address 
field of your browser and access the college where I teach.) 


We will learn how to use the Java InetAddress class to find the domain 
name corresponding to an IP address, and to find the IP address 
corresponding to a domain name. 


What is Your IP Address? 
Do you have an IP address and a domain name ? 


If (like me) you use a commercial Internet Service Provider (ISP) for your 
Internet service at home, you probably don't have a fixed IP address or a 
fixed domain name . Rather, the ISP has a block of IP addresses reserved. 
When you subscribe to the ISP, the ISP temporarily assigns an IP address to 
you. That IP address may or may not change over time, but probably will 
change unless you pay the extra fee for a fixed IP address. 


On the other hand, I currently pay for server space from a company in 
North Carolina under the domain name www.dickbaldwin.com . My 
domain has an IP address of 98.129.229.162 . For as long as I continue to 
pay the bill, that domain name and that IP address will be assigned to me 
for use as my personal website. 


I suppose that the company could change the IP address at some 
point provided that they make certain that all of the domain name 
servers get updated to reflect the new IP address that corresponds 
to the domain name. 


Ports 


Each server computer that you may connect to will be logically organized 
into ports . These are not physical ports in the sense of the VGA or HDMI 
port on the back of your computer. Rather, they are simply logical sub- 
addresses which you provide to the operating system on the server so that 
the operating system can cause the appropriate server software to "answer 
the call." We will write a simple server software package that will service 
several different ports on independent threads in a future module. 


One of the Java books on my bookshelf refers to the IP address as being 
analogous to the telephone number of a company and the port to be 
analogous to the employee's telephone extension within that company. (At 
least that is how telephone systems in companies were organized when I 
was working in industry.) 


Theoretically, there are 65,535 available ports. Port numbers between 1 and 
1023 are predefined to be used for certain standard services. For example, if 
you want to connect with server software that communicates using the 
HTTP protocol, you would normally connect to port 80 on the server of 
interest. 


Similarly, if you want to connect to a port that will tell you the time, you 
should connect to port 13, assuming that you can find a server somewhere 
that is willing to support port 13. If you want to connect to a port that will 
simply echo whatever you send to it (usually for test purposes) , you should 
connect to port 7. We will write Java applications that connect to all of 
these ports. 


In the interest of brevity, I am not going to provide a complete list of ports 
and their services. However, you should be able to find all the information 
you might need about port numbers and the services they support by 

starting your favorite search engine and searching for " well known ports" 


vy 


Firewalls 


You may have heard about firewalls . A firewall is the common name given 
to the equipment and associated software that is used to insulate the 
network inside of a company from the Internet at large outside the 
company. Typically, the firewall will restrict the degree to which computers 
inside the company can communicate with the Internet for security and 
other reasons. 


Proxy Servers 


You may also have heard about proxy servers . A proxy server acts as an 
interface between computers inside the company and the Internet at large. 


Oftentimes the proxy server will have the ability to cache web pages for 
limited periods of time. For example, if ten people inside the company 
attempt to connect to the same Internet server and download the same web 
page within a (hopefully) short period of time, that page may be saved on 
the proxy server on the first attempt and then delivered to the next nine 
people without re-acquiring it from the outside web server. This can 
significantly improve delivery time and reduce network traffic into and out 
of the company. It can also result in the delivery of stale pages in some 
cases. 


Standards and Protocols 


At some point, you may be interested in obtaining technical information 
about Internet standards and protocol specifications. A good place to start 


looking for such information is http://www.w3.org/pub/WWW/Protocols/ . 


URL 


URL is an acronym for Uniform Resource Locator . (It is also the name 
of a class in Java.) A URL is a pointer to a particular resource at a 
particular location on the Internet. A URL specifies the following: 


e the protocol used to access the server (such as http) 

e the name of the server 

e the port on the server (optional) 

e the path and name of a specific file on the server (sometimes optional) 
e the anchor or reference point within the file (optional) 


Sometimes the name of the file can be omitted, in which case an HTTP 
browser will usually append the file name index.html to the specified path 
and try to load that file. For example, as of this writing, you can connect to 
my home page on the HTTP server at Austin Community College using 
either of the following URLs: 


e http://www.austincc.edu/baldwin/ 
e http://www.austincc.edu/baldwin/index.html 


In addition to specifying the name of the file of interest, it is also sometimes 
possible to specify an anchor or reference that has been established inside 
the file. The anchor is identified by the text following the # character in the 
URL. 


For example, as of this writing, the following URL will take you to a 
specific location inside one of my modules on Java servlets. 


http://cnx.org/content/m48518/latest/#Images 


(Note the #Images at the end of the URL. That is commonly known as the 
anchor .) 


The general syntax of a URL is as follows: 


protocol://hostname[:port]/path/filename#ref 


The port is optional, and is not normally required if you are accessing a 


server that provides the required service on a standard port. The browser (or 


other software being used to connect) should know which port supports the 
specified protocol and should connect to that port by default. 


You could fill in the optional port number and use the following URL to 
access the same location in my servlets module, but that would simply 
require you to do some extra typing. 


http://cnx.org:80/content/m48518/latest/#Images 


However, if you were to change the 80 to a 25, you would not be able to 
connect and successfully communicate with the server because the server 
does not support the HTTP protocol on port 25. In fact, here is the text of 
the Firefox error message that resulted from me doing that: 


"This address is restricted This address uses a network port which 
is normally used for purposes other than Web browsing. Firefox 
has canceled the request for your protection." 


The Google Chrome browser simply provided the following error message 
when I attempted to do that. 


"This webpage is not available." 


When I clicked a "More" button on the Chrome error message, this is what I 


got: 


"The webpage at 
http://cnx.org:25/content/m48518/latest/#Images might be 


temporarily down or it may have moved permanently to a new 
web address. Error code: ERR_UNSAFE_PORT" 


Note, however, that we will be properly addressing port 8080 on a 
particular server in some future modules. Since 8080 is not a standard port, 
it will be necessary for us to enter the port number following a colon in 
order to access the material on the server. 


Socket Classes and the URL Class 


Java provides at least two different approaches for doing network 
programming (and possibly more) , insofar as the web is concerned. The 
two approaches are associated with 


e The Socket , DatagramSocket , and ServerSocket classes 
e The URL, URLEncoder, and URLConnection classes. 


Socket Programming 


Socket programming primarily makes use of two socket classes named 
Socket and DatagramSocket along with the ServerSocket class. The first 
two socket classes represent TCP and UDP communications respectively. 


Generally, the two socket classes are used to implement both clients and 
servers , while the ServerSocket class is only used to implement servers . 
We will see several examples of socket programming in this series of 
modules. 


Socket programming provides a low-level approach by which you can 
connect two computers for the exchange of data. One of those is generally 
considered to be the client while the other is considered to be the server . 


Although the distinction between client and server is becoming less clear 
each day, there is one fundamental distinction that is inherent in the Java 


programming language. 


The client initiates conversations with servers, while servers 
block and wait for a client to initiate a conversation. 


The governing application-level protocol will determine what happens after 
the connection is made and the conversation has begun. The fact that the 
two computers can connect doesn't necessarily mean that they can 
communicate. In order to communicate, they must implement some 
mutually acceptable application protocol 


For example, the fact that I can dial a telephone number for a telephone 
located in France doesn't mean that I can communicate with the person who 
answers the phone. I don't know how to speak the French language. Unless 
the person who answers the phone speaks English, very little 
communication is likely to take place. 


Socket programming has been around for quite a while in the Unix world. 
Java simply makes it easier by encapsulating much of the complexity of 
socket programming into classes, and allowing you to approach the task on 
an object-oriented basis. 


On the other hand, according to some authors, some of the generality and 
capability that Unix socket programmers have enjoyed has been lost in the 
encapsulation process. 


Basically, socket programming makes it possible for you to cause data to 
flow in a full-duplex mode between a client and a server. This data flow can 
be viewed in almost exactly the same way that we view data flow to and 
from a disk: as a stream of bytes. 


As with most stream data processing, the system is responsible for moving 
the bytes from the source to the destination. It is the responsibility of the 
programmer to assign meaning to those bytes. 


Assigning meaning takes on a special significance for socket programming. 
In particular, as mentioned above, it is the responsibility of the programmer 
to implement a mutually acceptable communication protocol at the 
application level to cause the data to flow in an orderly manner. 


An application protocol is a set of rules by which the programs in the two 
computers can carry on a conversation and transfer data in the process. For 
example, we will also write a program that implements a very abbreviated 
form of the HTTP protocol to download web pages from a server and 
display them. 


We will also write a program that functions as an (abbreviated) HTTP 
server to deliver web pages to a client and also supports the echo protocol 
for both TCP and UDP programming. 


Each of these programs will involve adherence to a fairly simple protocol. 
(At least the part that we implement will be fairly simple) . 


In addition, we will also write a program that obtains the date and time from 
another computer. In this case, the protocol will be about as simple as it can 
possibly be. The client will simply make the connection and listen for a 
string containing the date and time. This will be sort of like dialing the local 
time service, except that we won't have to listen to an advertisement before 
getting the time. 


The bottom line is that with socket programming, it is easy to write code 
that will cause a stream of bytes to flow in both directions between a client 
and a server. This is no more difficult than causing a stream of bytes to flow 
in both directions between memory and a file on a disk. 


However, getting the bytes to flow is the easy part. Beyond that, you must 


do all of the programming to implement an application protocol that is 
understood by both the client and the server. 


URL Programming 


URL programming occurs at a higher level than socket programming, and 
in theory represents a very powerful idea. 


In theory, by using the URL class, you can open a connection to a resource 
on the web, specified by a URL object, and simply call the getContent 
method on that URL object. The content of the resource will then be 
magically downloaded and will appear as an object on the client machine, 
even if it requires an application protocol that didn't exist when you wrote 
the program, and contains content that you didn't understand when you 
wrote the program. 


This description may be a bit of an overstatement, but it is pretty close to 
the claims being made. This is a powerful idea, which may or may not bear 
fruit in the future. 


If fully implemented by browsers, the idea means that you can place new 
and unusual material on a web site along with special content handlers and 
protocol handlers. Then a cooperating browser will use those special 
handlers to move that material from the web site to the client and interpret 
its content once it gets there without a requirement to install software (such 
as plug-ins) on the client computer on a permanent basis. 


Here is what Peter van der Linden has to say about this topic in his 
excellent book titled Just Java 1.1 and Beyond: 


"If a browser doesn't recognize a media type, it should be able to 
download the code to process it from the same place it got the 
file. If they ever get this working, it will be ... a good thing." 


Is it working, or will they ever get it working? I don't know. If it depends on 
cooperation among all the major players, including the major browser 
vendors - probably not. Therefore, I don't plan to spend much time on the 
topic of protocol and content handlers until I see some evidence that it is 
working to such an extent that it is practically useful. 


That is not to say that you couldn't use the capability right now if you were 
developing an intranet and wanted the clients to have access to new and 
unusual content. It would be necessary for you to provide the appropriate 
protocol and content handlers, and it would probably be necessary for the 
clients to run Java applications written by you instead of standard browsers 
to access the data. 


Also, the URL class provides an alternative way to connect one computer 
to another and transfer data on a stream basis, so we will see some 
examples of retrieving data from a server by obtaining a URL connection, 
and then opening and servicing I/O streams between the client and the 
server. We will see some sample programs that make use of this technique, 
but we will also see that it is somewhat redundant with the socket 
programming approach. 


A local area network 


This is part of a sub-collection of modules designed for teaching network 
programming. Therefore, you may find some of the modules more 
meaningful if you are able to connect two or more computers in a local area 
network and run the sample programs across the network. 


However, it is possible to simulate a network inside a single computer. If 
you are unable to create an actual network, you should be able to run all of 
the sample programs by simulating a network in your single computer. 


The operating system 


While the capabilities of Java are generally independent of the operating 
system in use, the manner in which an individual computer must be 
configured for network operation is generally not independent of the 
operating system. 


In those cases where these modules provide instructions for configuring the 
computer, those instructions will assume a Windows operating system. If 
you are using a different operating system, you will need to translate those 
instructions into your operating system. 


What's Next? 


We will learn how to use the Java InetAddress class to find the domain 
name corresponding to an IP address, and to find the IP address 
corresponding to a domain name in our sample program in the next module. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4620: General Information 
e File: Java4620.htm 

e Published: 03/02/14 

e Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 


Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4620r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4620: General Information in the Network Programming sub- 
collection. 


Table of Contents 


e Preface 
e Questions 


Odes dy Oey Oy Oe 2 ey Oy A, 1 1 I A ee i I 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4620: General Information in the Network Programming sub- 
collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 
True or False? 


A network is a group of computers and other devices that are connected in 
some fashion for the purpose of exchanging data. 


Go to answer 1 


Question 2 
True or False? 


Each of the devices on the network can be thought of as a node , and each 
node has the same address. 


Go to answer 2 


Question 3 
True or False? 
Modern networks transfer data using a concept known as packet switching . 


Go to answer 3 


Question 4 
True or False? 


In order for two or more computers connected to a network to be able to 
exchange data in an orderly manner, each computer must use a different 
protocol. The protocol defines the rules by which they communicate. 


Go to answer 4 


Question 5 
True or False? 


The HTTP protocol defines how web browsers and servers communicate 
and the SMTP protocol defines how some email is transferred 


Go to answer 5 


Question 6 
True or False? 
IP is an acronym that stands for Interconnection Protocol. 


Go to answer 6 


Question 7 
True or False? 


IP is a network protocol that moves packets of data from a source to a 
destination. As the name implies, this is the protocol normally used on the 
Internet. 


Go to answer 7 


Question 8 


True or False? 


The Transmission Control Protocol (‘TCP ) was added to IP to give each 
end of a connection the ability to acknowledge receipt of IP packets and to 
request retransmission of corrupted or lost packets. Also TCP makes it 
possible to put the packets back together at the destination in the same order 
that they were sent. 


Go to answer 8 


Question 9 
True or False? 


TCP and IP work together to provide a reliable method of encapsulating a 
message into data packets, sending the packets to a destination, and 
reconstructing the message from the packets at the destination. 


Go to answer 9 


Question 10 
True or False? 


The User Datagram Protocol ( UDP) is even more reliable than TCP/IP in 
guaranteeing that a series of packets will arrive in the right order. However, 
UDP involves a high level of overhead and the data transfer rate may be 
slow. 


Go to answer 10 


Question 11 


True or False? 


Every computer attached to an IP network has a unique address, typically 
consisting of four bytes or 32 bits. Efforts are underway to expand the 
number of possible unique addresses to a much larger number. The planned 
number is the number of unique addresses that can be represented with a 
128-bit address. 


Go to answer 11 


Question 12 

True or False? 

For human consumption, we usually convert the value of each of the IP 
address bytes to an unsigned decimal value and display them connected by 
periods to make them easier to remember. For example, a typical IP address 


might be 206.77.150.222 . 


Go to answer 12 


Question 13 
True or False? 
Most IP addresses have a corresponding name known as a domain name . 


Go to answer 13 


Question 14 
True or False? 


The Domain Name of a destination server is encapsulated into data packets 
and used by the internet protocol to route those packets from the source to 


the destination. 


Go to answer 14 


Question 15 
True or False? 


The Java InetAddress class can often be used to find the domain name 
corresponding to an IP address, and to find the IP address corresponding to 
a domain name. 


Go to answer 15 


Question 16 
True or False? 


Each server computer that you may connect to will be logically organized 
into ports . Theoretically, there are a large number of available ports. A 
subset of those port numbers are predefined to be used for certain standard 
services. For example, if you want to connect with a public server that 
communicates using the HTTP protocol, you would normally connect to 
port 80 on the server of interest. 


Go to answer 16 


Question 17 
True or False? 


A firewall is the common name given to the equipment and associated 
software that is used to improve the communication speed of computers 


inside of a company with the Internet at large outside the company. 


Go to answer 17 


Question 18 
True or False? 


A proxy server is the common name given to the equipment and associated 
software that is used to insulate the network inside of a company from the 
Internet at large outside the company. Typically, the firewall will restrict the 
degree to which computers inside the company can communicate with the 
Internet for security and other reasons. 


Go to answer 18 


Question 19 
True or False? 


URL is an acronym for Uniform Resource Locator . (It is also the name 
of a class in Java.) A URL is a pointer to a particular resource at a 
particular location on the Internet. 


Go to answer 19 


Question 20 
True or False? 
A URL specifies the following: 


e the protocol used to access the server (such as http) 
e the name of the server 


e the port on the server (optional) 
e the path and name of a specific file on the server (sometimes optional) 
e the anchor or reference point within the file (optional) 


Go to answer 20 


Question 21 
True or False? 


Java provides at least two different approaches for doing network 
programming (and possibly more) , insofar as the web is concerned. The 
two approaches are associated with 


e The Connector , DatagramConnector , and ServerConnector 
classes 
e The URL, URLEncoder, and URLConnection classes. 


Go to answer 21 


Question 22 
True or False? 


The two socket classes named Socket and DatagramSocket represent TCP 
and UDP communications respectively. 


Go to answer 22 


Question 23 


True or False? 


Generally, the Socket and DatagramSocket classes are used to implement 
both clients and servers , while the ServerSocket class is only used to 
implement servers . 


Go to answer 23 


Question 24 
True or False? 


Although the distinction between client and server is becoming less clear 
each day, there is one fundamental distinction that is inherent in the Java 
programming language. 


The server initiates conversations with clients, while clients block 
and wait for a server to initiate a conversation. 


Go to answer 24 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None eles 


Display your nametiere. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 24 


False. 


Although the distinction between client and server is becoming less clear 
each day, there is one fundamental distinction that is inherent in the Java 
programming language. 


The client initiates conversations with servers, while servers 
block and wait for a client to initiate a conversation. 


Go back to Question 24 


Answer 23 
True. 


Go back to Question 23 


Answer 22 
True. 


Go back to Question 22 


Answer 21 
False. 


Java provides at least two different approaches for doing network 
programming (and possibly more) , insofar as the web is concerned. The 
two approaches are associated with 


e The Socket , DatagramSocket , and ServerSocket classes 
e The URL, URLEncoder, and URLConnection classes. 


Go back to Question 21 


Answer 20 
True. 


Go back to Question 20 


Answer 19 
True. 


Go back to Question 19 


Answer 18 


False. A proxy server is often used to improve the communication speed of 
computers inside of a company with the Internet at large outside the 
company. For example, if ten people inside the company attempt to connect 
to the same Internet server and download the same web page within a 
(hopefully) short period of time, that page may be saved on the proxy server 
on the first attempt and then delivered to the next nine people without re- 
acquiring it from the outside web server. This can significantly improve 
delivery time and reduce network traffic into and out of the company. 


Go back to Question 18 


Answer 17 


False. A firewall is the common name given to the equipment and 
associated software that is used to insulate the network inside of a company 
from the Internet at large outside the company. Typically, the firewall will 


restrict the degree to which computers inside the company can 
communicate with the Internet for security and other reasons. 


Go back to Question 17 


Answer 16 
True. 


Go back to Question 16 


Answer 15 
True. 


Go back to Question 15 


Answer 14 


False. The Domain Name System (DNS) was developed to translate 
between IP addresses and domain names. Whenever you log your browser 
onto the internet and attempt to connect to a server using its domain name, 
the browser first communicates with a DNS server to learn the 
corresponding numeric IP address. The numeric IP address (and not the 
domain name) is encapsulated into the data packets and used by the internet 
protocol to route those packets from the source to the destination. 


Go back to Question 14 


Answer 13 


True. 


Go back to Question 13 


Answer 12 
True. 


Go back to Question 12 


Answer 11 
True. 


Go back to Question 11 


Answer 10 
False. The User Datagram Protocol ( UDP) is often referred to as an 
unreliable protocol because there is no guarantee that a series of packets 


will arrive in the right order, or that they will arrive at all. 


Go back to Question 10 


Answer 9 
True. 


Go back to Question 9 


Answer 8 


True. 


Go back to Question 8 


Answer 7 
True. 


Go back to Question 7 


Answer 6 
False. IP is an acronym that stands for Internet Protocol. 


Go back to Question 6 


Answer 5 
True. 


Go back to Question 5 


Answer 4 


False. In order for two or more computers connected to a network to be able 
to exchange data in an orderly manner, they must adhere to a mutually 
acceptable communication protocol. The protocol defines the rules by 
which they communicate. 


Go back to Question 4 


Answer 3 
True. 


Go back to Question 3 


Answer 2 


False. Each of the devices on the network can be thought of as a node , and 
each node has a unique address. 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4620r-Review 
e File: Java4620r.htm 

e Published: 03/08/14 

e Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4630: The InetAddress Class 
This module explains the use of the InetAddress class. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


¢ General background information 
e Discussion and sample code 

e Run the program 

e What's next? 

e Miscellaneous 

¢ Complete program listing 


Preface 


This module is one in a collection of modules designed for teaching INEW 2338 
Advanced Java (Web) at Austin Community College in Austin, TX. More 
specifically, it is one in a sub-collection of modules designed for teaching 
network programming in that course. The purpose of this module is to introduce 
the student to the InetAddress class that can be used to deal with IP addresses 
and domain names . 


Viewing tip 


I recommend that you open another copy of this module in a separate browser 
window and use the following links to easily find and view the Figures and 
Listings while you are reading about them. 


Figures 


e Figure 1. Program output. 


e Figure 2. The list of Google IP addresses. 

e Figure 3. The IP Address for my localhost. 

e Figure 4. Name and IP address of my localhost. 

e Figure 5. Canonical host name for Google. 

e Figure 6. Google host name using reverse lookup. 


Listings 


e Listing 1. Beginning of the program. 

e Listing 2. Display the Google InetAddress objects. 

e Listing 3. Get InetAddress object for localhost. 

e Listing 4. Extract name and IP address of my localhost. 

e Listing 5. Get and display canonical host name for Google. 
e Listing 6. Do a reverse lookup on Google. 

e Listing 7. End of the program. 

e Listing 8. Complete program listing. 


General background information 


Every computer attached to an IP network has a unique 32-bit or 128-bit IP 
address. 


For human consumption, we usually convert each of the bytes in the IP address 
to an unsigned decimal value and display them connected by periods to make 
them easier to remember. As of this writing, the IP address of www.austincc.edu 
(the college where I teach) is 206.77.150.222. 


The domain name 
What do we mean when we speak of www.austincc.edu_? 


Each IP address can have a corresponding name known as a domain name . The 
domain name for the IP address 206.77.150.222 is www.austincc.edu . 


For example, I can enter either the IP address or the domain name into the 
address field of my browser and use it to connect to the ACC web site. 


The Domain Name System (DNS) 


The Domain Name System (DNS) was developed to translate between IP 
addresses and domain names. Whenever you log your browser onto the internet 
and attempt to connect to a server using its domain name , the browser first 
communicates with a DNS server to learn the corresponding numeric IP address. 
The numeric IP address is encapsulated into the data packets and used by the 
internet protocol to route those packets from the source to the destination. 


The InetAddress class 


We will learn how to use methods of the Java InetAddress class to find the IP 
address corresponding to a domain name in this module. 


We will learn how to find the canonical host name for a given domain name. 
We will learn how to obtain information about the localhost . 


We will learn how to do a reverse lookup to find the canonical host name 
associated with an IP address. 


Methods of the InetAddress class 


The InetAddress class provides several static methods that return a reference to 
an object of type InetAddress . You can use those methods to deal with and to 
manipulate IP addresses and domain names. 


For example, the static getByName(String host) method returns a reference to 
an InetAddress object representing the host whose domain name is passed as a 
parameter to the method. The resulting object can be used to determine the IP 
address and the canonical host name of the host. 


There is a problem with this, however. As I will explain later, many hosts have 
multiple IP addresses. To accommodate this, the InetAddress class provides a 
method named getAlIByName(String host) that can be used to get an array of 
references to InetAddress objects representing IP addresses assigned to the host. 


The getLocalHost method returns a reference to an InetAddress object 
representing the local host computer. 


There are also a variety of methods that can be called on an InetAddress object 
to get information about the host that is represented by that object. 


Discussion and sample code 


I will present and explain a program named Java4630a that illustrates various 
aspects of the InetAddress class in this module. 


I will explain the program in fragments. A complete listing of the program is 
provided in Listing 8 . 


The program output 
The program produces the screen output shown in Figure 1 when run on my 


computer. However, the information regarding the LocalHost will be different 
when you run this program on your computer. 


Figure 1 - Program output. 


Figure 1 - Program output. 


Get and display InetAddress(es) of Google URL 
www.google.com/173.194.115.17 
www.google.com/173.194.115.18 
www.google.com/173.194.115.19 
www.google.com/173.194.115.20 
www.google.com/173.194.115.16 


Get and display current InetAddress of LocalHost 
de118700/192.168.2.16 


Extract and display current name of LocalHost 
de118700 


Extract and display current address of LocalHost 
192.168.2.16 


Display canonical host name for Google 
dfw06s39-in-f17.1e100.net 

Display Google name using reverse lookup. 
dfw06s39-in-f17.1e100.net 
dfw06s39-in-f17.1e100.net 


I will refer to this output in context as I explain the various elements of the 
program. 


Beginning of the program 


This is a very simple program consisting solely of the main method in a class 
named Java4630a . The program begins in Listing 1 . 


Listing 1 - Beginning of the program. 


import java.net.*; 


class Java4630a{ 
public static void main(String[] args){ 
try{ 
System. out.printin( 
"Get and display InetAddress(es) of 
Google URL"); 
InetAddress[] addresses = 


InetAddress.getAl1ByName("www.google.com"); 


Domain names and IP addresses 


There is not necessarily a one-to-one correspondence between IP addresses and 
domain names. In fact there can be a many-to-one correspondence between the 
two. 


Every computer on the Internet must have a unique IP address, but multiple 
computers can have (or can respond to) the same domain name. For example, if 
the domain name, www.google.com, were required to apply to a single 
computer, that computer would require an enormous amount of bandwidth and 
processing power to accommodate all of the search requests that are made to that 
domain name every second of every day. 


The getAlIByName method 


The InetAddress class provides a static method named getAllIByName that 
takes the domain name of a host as an incoming parameter and returns an array 
containing references to one or more objects of type InetAddress . Each object 
contains an IP address and some other information related to the domain name. 
The set of InetAddress objects in the array contain all of the IP addresses that 
are currently assigned to that domain name. 


Get all for Google 


The code in Listing 1 calls the getAllIByName method passing the domain name 
for Google as a parameter. It receives a reference to an array containing 
references to one or more InetAddress objects. The set of InetAddress objects 
encapsulate a list of five IP addresses that are currently assigned to Google. 


Display the InetAddress objects 


Listing 2 contains a for loop that displays the toString version of the information 
encapsulated in each of the InetAddress objects. 


Listing 2 - Display the Google InetAddress objects. 


for(int cnt=0; cnt<addresses.length;cnt++) { 
System.out.printin(addresses[cnt]); 
}//end for loop 


Figure 2 shows the output produced by Listing 1 and Listing 2 . 


Figure 2 - The list of Google IP addresses. 


Get and display InetAddress(es) of Google URL 
www.google.com/173.194.115.83 
www.google.com/173.194.115.84 
www.google.com/173.194.115.80 
www.google.com/173.194.115.81 
www.google.com/173.194.115.82 


Everything to the left of the slash in the last five lines of Figure 2 shows the 
domain name. Everything to the right of the slash shows the IP addresses. Note 
that there are duplicate domain names but there are no duplicate IP addresses. 


Why only five IP addresses? 


I was surprised that there are only five IP addresses in the list. Surely Google 
needs more than five front-end computers to handle the thousands of incoming 
requests that it receives every second of every day. 


Upon further investigation I noticed that if I run the same program over and over, 
I am likely to get different sets of five IP addresses on different runs. This 
suggests that in some fashion, the getAllByName method limits the number of 
InetAddress objects to only five of the potentially hundreds of IP addresses that 
are assigned to a particular host. However, this is not mentioned in the Oracle 
documentation. The documentation states: 


"Given the name of a host, returns an array of its IP addresses, based 
on the configured name service on the system." 


There is clearly more going on here than I understand. 
The localhost 


The computer that you are using to read this module online also has an IP 
address and a name. The IP address, the name, and perhaps some other things as 
well are grouped together under something commonly referred to as localhost . 
In other words, the IP address of your localhost is the IP address of the computer 
that you are using to read this module. 


Get InetAddress object for localhost 


The code in Listing 3 calls the static getLocalHost method of the InetAddress 
class to get a reference to an InetAddress object representing the computer that I 
was using when I wrote this module. 


Then it passes that object's reference to the println method causing the 
overridden toString method belonging the InetAddress object to be executed. 


Listing 3 - Get InetAddress object for localhost. 


System.out.println();//blank line 

System.out.println("Get and display current 
+ 

"InetAddress of 

LocalHost"); 

InetAddress address = 
InetAddress.getLocalHost()/; 

System.out.println(address); 


The screen output for localhost 


The string returned by the overridden toString method of the InetAddress 
object is shown by the second line in Figure 3 . 


Figure 3 - The IP Address for my localhost. 


Get and display current InetAddress of LocalHost 
de118700/192.168.2.16 


Everything to the left of the slash is the name of the computer. Everything to the 
right of the slash is the IP address. 


A local area network 
Note that this is not the IP address by which the world sees my computer on the 


Internet. Instead, this is one of several computers on a local area network. This is 
the address that was assigned to this computer by the network router. 


I can find the IP address that my cable modem presents to the world by entering 
the following text into the Google search box without the quotation marks: "get 
ip address" 


As you can see, the second line in Figure 3 contains both the name and the IP 
address separated by a slash character. 


Extract name and IP address of my localhost 


Assume that you have a reference to an InetAddress object and for some reason 
you need to extract the name and IP address as separate String objects. (We will 
need to do this in a future module.) The InetAddress class provides two methods 
that allow you to do that. 


The code in Listing 4 calls the getHostName and the getHostAddress methods 
on the reference to the InetAddress object and displays the strings returned by 
those methods. 


Listing 4 - Extract name and IP address of my localhost. 


Listing 4 - Extract name and IP address of my localhost. 


System. 
System. 


Current " + 


LocalHost"); 


System. 


System. 
System. 


Current " + 


LocalHost"); 


out. 
out. 


out 


out. 
out. 


println();//blank line 
println("Extract and display 


"name of 


.printin(address.getHostName()); 


println();//blank line 
println("Extract and display 


"address of 


System.out.println(address.getHostAddress()); 


The code in Listing 4 produces the output shown in Figure 4 . 


Figure 4 - Name and IP address of my localhost. 


Extract and display current name of LocalHost 


de118700 


Extract and display current address of LocalHost 


192.168.2.16 


But, we already knew the answer 


Of course, we already knew what the output would be based on the toString 
output in Figure 3. The difference is that in Figure 3 , we only have that 
information as part of something that is displayed on the screen. The code in 
Listing 4 gives us that same information in the form of String objects that we 
can use for some purpose other than simply looking at the information on the 
screen. (See googleAddress in Listing_6 for example.) 


Canonical host name 
The documentation describes the method named getCanonicalHostName 


partially as follows: 


"Gets the fully qualified domain name for this IP address. Best effort 
method, meaning we may not be able to return the FQDN depending 
on the underlying system configuration." 


One online description for a canonical host name reads as follows: 


"A host machine on a network can be identified by several different 
names. However, each host must have one official hostname. All other 
hostnames are considered aliases of the canonical hostname" 


Get and display canonical host name for Google 


Returning now to Google, the code in Listing 5 gets and displays the canonical 
hostname for Google. 


Listing 5 - Get and display canonical host name for Google. 


Listing 5 - Get and display canonical host name for Google. 


System. out.printin( 
"Display canonical host name for 
Google"); 
//Get InetAddress containing one of Google's 
// IP addresses. 
address = 
InetAddress.getByName("www.google.com"); 


System.out.println(address.getCanonicalHostName()); 


The code in Listing 5 begins by getting a reference to one of the InetAddress 
objects that represent www.google.com . Then the getCanonicalHostName 
method is called on that object to get and display the canonical host name. The 
code in Listing 5 produces the output shown in Figure 5. 


Figure 5 - Canonical host name for Google. 


Display canonical host name for Google 
dfw06s39-in-f17.1e100.net 


As you can see, this canonical host name wouldn't mean much to a human 
observer. 


Other canonical host names 


Here is a list of some canonical host names that can be obtained using code 
similar to that shown in Figure 5. Try pasting them into your browser's address 


window and pressing the Enter key to see which ones access the sites that you 
expect and which ones don't . 


* www.google.com : dfw06s39-in-f17.1e100.net 

* www.amazon.com : (No canonical host name was returned.) 

¢ www.yahoo.com : ir2.fp.vip.bf1.yahoo.com 

¢ www.dickbaldwin.com : (No canonical host name was returned.) 

¢ www.whitehouse.gov_: (No canonical host name was retummed.) 

¢ www.healthcare.gov : a23-207-26- 
194.deploy.static.akamaitechnologies.com 

* www.austincc.edu : m20677150222.austincc.edu 

* www.ebay.com : www.ebay.com 

° www.facebook.com : edge-star-shv-02-dfw1.facebook.com 

* www.twitter.com : (No canonical host name was returned.) 

¢ www.foxnews.com : a96-17-203-72.deploy.akamaitechnologies.com 

* www.cbsnews.com : a96-17-203-90.deploy.akamaitechnologies.com 


Reverse lookup 


At one point in the history of Java, it was possible to call the getByName 
method passing the IP address as a string to do a reverse lookup on an IP address. 
The method would return the domain name to which the IP address was 
assigned. However, this changed around Java version 1.4 and some additional 
code is now required to do a reverse lookup. 


Do a reverse lookup on Google 
Listing 6 does a reverse lookup on Google by passing one of the IP addresses to 
the getByName method and then calling the following methods on the 


InetAddress object that is returned: 


e getHostName 
e getCanonicalHostName 


Listing 6 - Do a reverse lookup on Google. 


Listing 6 - Do a reverse lookup on Google. 


System. out.printin( 
"Display Google name using reverse 
lookup."); 
String googleAddress = 
address.getHostAddress(); 
System.out.println(InetAddress.getByName( 


googleAddress).getHostName()); 
System.out.println(InetAddress.getByName( 


googleAddress).getCanonicalHostName()); 


The code in Listing 6 produces the output shown in Figure 6. 


Figure 6 - Google host name using reverse lookup. 


Display Google name using reverse lookup. 
dfw06s39-in-f17.1e100.net 
dfw06s39-in-f17.1e100.net 


The canonical host name 


To me, the most interesting thing in Figure 6 is that both methods return the 
canonical host name. Neither method returns the domain name. 


Although it isn't shown here, calling the getHostName method on one of the 
InetAddress objects contained in the addresses array in Listing 1 returns the 
domain name or www.google.com . Calling the getCanonicalHostName on the 
same InetAddress object returns the canonical name shown in Figure 5. 


Apparently when you create an InetAddress object on the basis of the domain 
name, the object knows both the domain name and the canonical host name. 
However, when you create an InetAddress object using the IP address, the only 
name that it knows is the canonical host name. 


The InetAddress class also has a method named getByAddress that 
apparently provides the same behavior when the IP address is 
converted to an array of bytes and passed to the method in that format. 
However, I haven't tested that method. 


Can you access the site with the canonical host name 


With respect to Google, the canonical host name, the domain name, or one of the 
IP addresses can be used in your browser address field to access the site. 


However, for those websites in the above list that have a canonical name that 
ends with akamaitechnologies.com , it appears that you cannot use either the 
canonical name or the IP address to access the web site. (I will leave it as an 
exercise for the student to investigate this further.) 


The end of the program 


The code in Listing 7 takes care of the administrative details necessary to 
properly end the program. 


Listing 7 - End of the program. 


Listing 7 - End of the program. 


}catch(UnknownHostException e){ 
e.printStackTrace(); 
}//end catch 


}//end main 
}//end class Java4630a 


Run the program 


I encourage you to copy the code from Listing 8. Compile the code and execute 
it while you are connected to the Internet. Experiment with the code, making 
changes, and observing the results of your changes. Make certain that you can 
explain why your changes behave as they do. 


What's next? 


The next module will deal with the URL class and the URLEncoder class. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


Module name: Java4630: The InetAddress Class 
File: Java4630.htm 

Published: 03/02/14 

Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to download 
a PDF file for this module at no charge, and also makes it possible for you to 
purchase a pre-printed version of the PDF file, you should be aware that some of 
the HTML elements in this module may not translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 

In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales nor do 
I know who does receive compensation. If you purchase such a book, please be 
aware that it is a copy of a module that is freely available on cnx.org and that it 
was made and published without my prior knowledge. 

Affiliation : | am a professor of Computer Information Technology at Austin 
Community College in Austin, TX. 


Complete program listing 


Listing 8 - Complete program listing. 


/*File Java4630a.java Copyright 1998, R.G.Baldwin 
Revised 01/03/14 


This program exercises several of the methods of the 
InetAddress class. 


KKEKKKKKRKKKRKE KKK KEKE KKK KKEKR KKK KEKE KK KKK KEKE KKK KKK KKK KKKKEKKEKKEKKE 


Ra ho 


import java.net.*; 


public class Java4630a{ 
public static void main(String[] args) { 
try{ 
System. out.println( 
"Get and display InetAddress(es) of Google 
URL"); 
InetAddress[] addresses = 


InetAddress.getAl1ByName( "www.google.com" ); 
for(int cnt=0; cnt<addresses.length;cnt++) { 
System.out.println(addresses[cnt]); 
}//end for Loop 


System.out.printin();//blank line 
System.out.println("Get and display current " + 
"InetAddress of 
LocalHost"); 
InetAddress address = 
InetAddress.getLocalHost(); 
System.out.printiln(address); 


System.out.println();//blank line 
System.out.printin( "Extract and display current 
Wt + 
"name of 
LocalHost"); 
System.out.printiln(address.getHostName()); 


System.out.printin();//blank line 
System.out.printin( "Extract and display current 
Wt + 
"address of 
LocalHost"); 
System.out.printiln(address.getHostAddress()); 


System.out.printin();//blank line 
System.out.printin( 
"Display canonical host name for 

Google"); 

//Get InetAddress containing one of Google's 

// IP addresses. 

address = 
InetAddress.getByName("www.google.com"); 


System.out.println(address.getCanonicalHostName() ); 
System.out.println( 
"Display Google name using reverse 


lookup."); 
String googleAddress = address.getHostAddress(); 
System. out.println(InetAddress.getByName( 


googleAddress).getHostName()); 
System.out.printiln(InetAddress.getByName( 


googleAddress) .getCanonicalHostName()); 
}catch(UnknownHostException e){ 
e.printStackTrace(); 
}//end catch 


}//end main 
}//end class Java4630a 


-end- 


Java4630r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4630: The InetAddress Class in the Network Programming sub- 
collection. 


Table of Contents 


e Preface 
e Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INE W 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4630: The InetAddress Class in the Network Programming sub- 


collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


The Java InetAddress class can be used to find the IP address 
corresponding to a domain name . 


Go to answer 1 


Question 2 
True or False? 


Many hosts have multiple IP addresses. To accommodate this, the 
InetAddress class provides a method named getByName that can be used 
to get an array of references to InetAddress objects representing IP 
addresses assigned to the host. 


Go to answer 2 


Question 3 

True or False? 

The getByName method of the InetAddress class returns a reference to an 
InetAddress object representing the host whose domain name is passed as 


a parameter to the method. 


Go to answer 3 


Question 4 
True or False? 


The getLocalHost method of the InetAddress class returns a reference to 
an array of InetAddress objects representing all of the computers on the 


local area network. 


Go to answer 4 


Question 5 
True or False? 


There is a one-to-one correspondence between IP addresses and domain 
names. 


Go to answer 5 


Question 6 
True or False? 


Every computer on the Internet must have a unique IP address, but multiple 
computers can have (or can respond to) the same domain name. 


Go to answer 6 


Question 7 
True or False? 


The computer that you are using to read this module online also has an IP 
address and a name. The IP address, the name, and perhaps some other 
things as well are grouped together under something commonly referred to 
as localhost . In other words, the IP address of your localhost is the IP 
address of the computer that you are using to read this module. 


Go to answer 7 


What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None C eX) 


Display your nameifieke. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 7 
True. 


Go back to Question 7 


Answer 6 
True. 


Go back to Question 6 


Answer 5 


False. There is not necessarily a one-to-one correspondence between IP 
addresses and domain names. In fact there can be a many-to-one 
correspondence between the two. 


Go back to Question 5 


Answer 4 


False. The getLocalHost method of the InetAddress class returns a 
reference to an InetAddress object representing the local host computer. 


Go back to Question 4 


Answer 3 


True. 


Go back to Question 3 


Answer 2 


False. Many hosts have multiple IP addresses. To accommodate this, the 

InetAddress class provides a method named getAllByName that can be 

used to get an array of references to InetAddress objects representing all 
(or at least some) of the IP addresses assigned to the host. 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4630r-Review 
e File: Java4630r.htm 

e Published: 03/08/14 

e Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4640: The URL Class and the URLEncoder Class 
This module explains the use of the URL class and the URLEncoder class. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
» Listings 


¢ General background information 
e Discussion and sample code 


o The program Java4640a 
o The program Java4640d 


e Run the programs 

e What's next? 

e Miscellaneous 

¢ Complete program listings 


Preface 


This module is one in a collection of modules designed for teaching INEW 2338 Advanced Java 
(Web) at Austin Community College in Austin, TX. More specifically, it is one in a sub- 
collection of modules designed for teaching network programming in that course. The purpose of 
this module is to introduce the student to the URL class and the URLEncoder class. 


Viewing tip 


I recommend that you open another copy of this module in a separate browser window and use 
the following links to easily find and view the Figures and Listings while you are reading about 
them. 


Figures 


e Figure 1. General syntax of a URL. 

e Figure 2. Screen output from the program named Java4640a. 
e Figure 3. Program output for string-parameter constructor. 

e Figure 4. Building an absolute URL. 

e Figure 5. An encoded string. 

e Figure 6. Encoding rules. 

e Figure 7. Program output. 


Listings 


e Listing 1. The method named display. 

e Listing 2. Beginning of the program named Java4640a. 
¢ Listing 3. Building an absolute URL. 

e Listing 4. The URLEncoder.encode method. 

e Listing 5. Beginning of the program named Java4640d. 
e Listing 6. Open a connection to the URL. 

e Listing 7. Read and display the data. 

e Listing 8. The program named Java4640a. 

e Listing 9. The program named Java4640d. 


General background information 
What is a URL? 


URL is an acronym for Uniform Resource Locator. It is also the name of a class in Java, which is 
the primary topic for this module. 


A URL is a pointer to a particular resource at a particular location on the Internet. As you learned 
in an earlier module, a URL specifies the following : 


¢ protocol used to access the server (such as http), 

e name of the server, 

¢ port on the server (optional) 

e path and name of a specific file on the server (sometimes optional) 
e anchor or reference within the file (optional) 


Sometimes the name of the file can be omitted, in which case an HTTP server may append the 
file name index.html to the specified path and try to load that file. For example, we will write a 
simple HTTP server in a future module that will attempt to deliver a file named index.html if the 
name of the file is omitted from the URL. 

In addition to specifying the name of the file of interest, it is also sometimes possible to specify 
an anchor or reference that has been established inside the file. An example of how to take 
advantage of this capability was provided in an earlier module. 


General syntax of a URL 


The general syntax of a URL is shown in Figure 1 . 


Figure 1 - General syntax of a URL. 


Figure 1 - General syntax of a URL. 


protocol://hostname[ :port]/path/filename#ref 


The port number is optional, and is not normally required if you are accessing a server that 
provides the required service on a standard port. 


Two ways to do network programming 


Java provides at least two different ways to do network programming. The two ways are 
associated with socket classes and URL classes. The socket classes will be the topic of future 
modules. This module is concerned primarily with the URL class. 


A higher level approach 

URL programming occurs at a higher level than socket programming, and in theory represents 
some very powerful ideas. The powerful ideas represented by the advanced features of the URL 
class require an understanding of the development of protocol handlers and content handlers. I 


discussed this in some detail in an earlier module titled Java4620: General Information , and 
won't repeat that discussion here. 


A mundane alternative 
In addition to supporting the advanced concepts discussed in the earlier module, the URL class 


also provides a relatively mundane alternative way to connect one computer to another and 
transfer data on a stream basis. This module is primarily based on this capability. 


Discussion and sample code 


I will explain the programs named Java4640a and Java4640d in fragments. Complete listings of 
both programs are provided in Listing 8 and Listing 9 . 


The program Java4640a 
This program exercises four of the constructors and six of the methods of the URL class. 


The program also illustrates the use of the URLEncoder class to convert a string containing 
spaces and other such characters into a UTF-8 encoded string format. 


Screen output from the program named Java4640a 


The output from the program is shown in Figure 2. I will refer to portions of this output while 
discussing the program. 


Figure 2 - Screen output from the program named Java4640a. 


Use simple string constructor for host URL 
http www.austincc.edu -1 null 
http: //www.austincc.edu 


Use simple string constructor for host plus file 
http www.austincc.edu -1 /baldwin null 
http: //www.austincc.edu/baldwin 


Use strings for protocol, host, and file 
http www.austincc.edu -1 /baldwin null 
http://www. austincc.edu/baldwin 


Use strings for protocol host, and file 
and int for port 

http www.austincc.edu 80 /baldwin null 
http://www. austincc.edu:80/baldwin 


Construct absolute URL from host URL and relative URL 
http www.austincc.edu -1 /baldwin/Index.html null 
http://www. austincc.edu/baldwin/Index.html 


Now use URLEncoder to create UTF-8 encoded String 
http://space .tilde~.plus+.com 
ht tp%3A%2F%2Fspace+. tilde%7E.plus%2B.com 


The method named display 


The code in Listing 1 is a method named display that I wrote to illustrate some of the methods of 
the URL class, and also to serve the practical needs of displaying information contained ina URL 
object. 


Listing 1 - The method named display. 


Listing 1 - The method named display. 


void display(URL url){//method to display parts of URL 
System.out.print(url.getProtocol() + " "); 
System.out.print(url.getHost() + " "); 
System.out.print(url.getPort() + " "); 
System.out.print(url.getFile() + " "); 
System.out.printin(url.getRef()); 


//Now display entire URL as a string. 
System.out.printin(url.toString()); 
System.out.printin(); 

}//end display 


This method receives a reference to a URL object as a parameter and displays its component parts 
separated by space characters. Then it uses the overridden toString method of the URL class to 
display the contents of the URL object as a single String object. 


The parts of the URL 


As you can see from Listing 1, there is a method available for extracting each of the parts of a 
URL that were identified in the above list . 


Beginning of the program named Java4640a 


Now that we know what the display method does, we can examine the code in the main method 
of the class. 


Listing 2 shows the beginning of the program named Java4640a and the beginning of the main 
method. 


Listing 2 - Beginning of the program named Java4640a. 


Listing 2 - Beginning of the program named Java4640a. 


import java.net.*; 
import java.io.*; 


class Java4640a{ 
public static void main(String[] args){ 
Java4640a obj = new Java4640a(); 
try{ 
System.out.println( 
"Use simple string constructor for host URL"); 
obj.display(new URL("http://www.austincc.edu")); 


Listing 2 illustrates the instantiation of a URL object using the version of the constructor that 
expects to receive the URL in string format. (I will ignore the exception handling code from these 
discussions for brevity.) 


Listing 2 begins by instantiating an object of the controlling class that can be used to access the 
display method. Then it instantiates a new URL object using the string-parameter version of the 
constructor and passes that object to the display method. 


As described above, the display method accesses each component part of the URL object and 
displays them separated by spaces. Then it displays the URL object using the overridden toString 
method. 


Program output for string-parameter constructor 


The code in Listing 2 produced the output shown in Figure 3 . 


Figure 3 - Program output for string-parameter constructor. 


Use simple string constructor for host URL 
http www.austincc.edu -1 null 
http: //www.austincc.edu 


The -1 in Figure 3 indicates that there was no port specification, and the null indicates that there 
was no file name specification in the URL passed to the constructor for the URL object. 


The code fragment in Listing 2 is followed by code that constructs the URL object using other 
overloaded versions of the constructor. Each overloaded version requires the URL information in 
different formats. You can view that code in Listing 8 . 


Building an absolute URL 


I will to skip that code and move down to a more interesting case as shown by the fragment in 
Listing 3. 


Listing 3 - Building an absolute URL. 


System.out.println("Construct absolute URL from " + 
"host URL and relative URL"); 
URL baseURL = new URL( 
"http://www.austincc.edu/baldwin/hello.html"); 
obj .display(new URL(baseURL, "/baldwin/Index.htm1") ); 


Listing 3 uses a URL constructor that requires two parameters: a URL object and a String object. 
Here is part of the somewhat cryptic description of this constructor from the Oracle 
documentation. 


"Creates a URL by parsing the given spec within a specified context. The new URL is 
created from the given context URL and the spec argument as described in RFC2396 
"Uniform Resource Identifiers : Generic * Syntax" : " 


What does this mean? 


Let me try to explain this constructor in my own words (with some help from Elliotte Rusty 
Harold) . You can use this constructor to build an absolute URL from a relative URL . 


Assume, for example, that you have written your own method to display HTML files the way that 
they are displayed by a browser rather than simply as a text file. Such files often contain links to 
relative URL's . In such a case, the link would be provided simply as a path and file name under 
the assumption that the path and file name can be found relative to the base URL containing the 
HTML file. 


According to Java Network Programming by Elliotte Rusty Harold, 


"In this case, you use the URL to the document that contains the link to provide the 
missing information." 


The construction process 


The code in Listing 3 constructs a base URL object pointing to 


"http://www.austincc.edu/baldwin/hello.html" 


Then it uses the version of the constructor currently under discussion to combine that base URL 
object with a relative URL given by 


"/baldwin/Index.html" 


This produces the URL object displayed in Figure 4 . 


Figure 4 - Building an absolute URL. 


Construct absolute URL from host URL and relative URL 
http www.austincc.edu -1 /baldwin/Index.html null 
http://www. austincc. edu/baldwin/Index. html 


Hopefully this example illustrates how the constructor can combine a base URL object with a 
relative URL to produce a new URL object that is an absolute pointer to the relative URL. 


The URLEncoder class 


There is one more issue that we need to examine before leaving this program: the URLEncoder 
class. This class is provided to help deal with problems arising from spaces, special characters, 
non-alphanumeric characters, etc. , that some operating systems may allow in file names but 
which may not be allowed in a URL. 


If you need to create a URL object using a URL string that has these problems, you should first 
use the encode method of the URLEncoder class to convert it into an acceptable URL string. 


The URLEncoder.encode method 


This class provides a static method named encode that encodes a string representation of a URL 
into an acceptable format. 


(Technically I believe it is correct to say that the format produced in Listing 4 is 
"application/x-www-form-urlencoded" and the binary encoding is UTF-8.) 


The encode method returns a String object that is a cleaned-up version of the original string. 


Listing 4 calls the encode method to encode a string that was purposely constructed to contain 
several unsafe characters. It displays both the raw string and the encoded string for comparison. 


Listing 4 - The URLEncoder.encode method. 


System.out.println("Now use URLEncoder to create " + 
"UTF-8 encoded String"); 
System.out.printin("http://space .tilde~.plus+.com"); 
System.out.printiln(URLEncoder . encode( 
"http://space .tilde~.plus+.com", "UTF-8")); 


The encoded output 


The output from the code in Listing 4 is shown in Figure 5 . 


Figure 5 - An encoded string. 


Now use URLEncoder to create UTF-8 encoded String 
http://space .tilde~.plus+.com 
ht tp%3A%2F%2Fspace+. tilde%7E.plus%2B.com 


The encoded version doesn't mean a lot to a human, but it is a format that is acceptable across a 
wide variety of computers. In case you are interested, the encoding rules are shown in Figure 6 . 


Figure 6 - Encoding rules. 


To convert a String, each character is examined in turn: 
The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same. 
The space character '' is converted into a plus sign '+'. 


All other characters are converted into the 3-character string "%xy", where xy is the two- 
digit hexadecimal representation of the lower 8-bits of the character. 


Elliotte Rusty Harold provides a URLDecoder class in his Java Network Programming book that 
takes a URL string in the format shown above and converts it back to its String representation. 


The program Java4640d 


Now it is time to put some of what you have learned to work with a program named Java4640d . 
Once again, I will explain this program in fragments. A complete listing is provided in Listing 9 . 


This program illustrates using a URL object to connect to a URL and to read a file from that URL 
as an input stream. As we will see later, we can and will do the same thing using sockets in future 


modules. 


Your computer must be online for this program to run properly. Otherwise, it will throw an 
exception of type UnknownHostException . 


Program output 
The output from the program is a display of the contents of the file named page1.html in a raw 


text format. Thus, all of the HTML tags are visible. 


(Of course, you can modify the program to download and display a different file on the 
same or a different website.) 


As of January 2014, the output for the beginning of the file was as shown in Figure 7. (The file is 
much longer than that shown.) 


(I may modify the contents of this file from time to time, so if you compile and run this 
program later, you may get different results.) 


Figure 7 - Program output. 


<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> 
<html> 

<head> 

<meta http-equiv="Content-Type" content="text/html; 
charset=iso-8859-1"> 

<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; I) 
[Netscape]"> 

<title>Java and JavaScript Programming, by Richard G 
Baldwin</title> 

</head> 

<body bgcolor="#FFFFFF" link="#0000FF" vlink="#FFO000" 
lang="EN-US"> 


<hi> 

Baldwin's Test Page 1</h1> 

Click <a 
href="http://www2.austin.cc.tx.us/baldwin/page2.htm1">here</a> 
to view page 2 

<p>Note: The material on this page is not intended to be of 
any particular 


value. This file is posted for the purpose of testing HTTP 
network 

programs only. 

<p>The following red bar is a centered gif file. 

<center> 

<p><img SRC="red_thick_line_1.gif" BORDER=0 id="_x0000_i11025" 
height=9 width=300 

></center> 


<center> 


<h2> 
The following is a centered two-column table</h2></center> 


The beginning of the program 


The program begins in Listing 5. 


Listing 5 - Beginning of the program named Java4640d. 


import java.net.*; 
import java.io.*; 


class Java4640d{ 
public static void main(String[] args){ 
String dataLine; 
try{ 
//Get a URL object 
URL url = new URL( 
"http://www.austincc.edu/baldwin/pagei.htm1"); 


As before, I will ignore the exception-handling code while discussing this program. 
Create a URL object 


As you saw in the previous program, the URL class has several different constructors, each of 
which can create anew URL object on the basis of URL information provided as parameters to 
the constructor. The constructors differ in terms of how the URL information is provided. 


Listing 5 creates a URL object that points to the file named page1.html in the directory named 
baldwin on the server at Austin Community College where I teach. 


No port was specified 


The URL object will not contain a port specification because I didn't provide a port number. Later 
when we use one of the methods of the URL class along with this URL object to make a 
connection to the server, the connection will, by default, be made to port 80 which is the standard 
port for servers that support the HTTP protocol. 


In other words, when the port is not provided (the URL object contains a port number of -1) , the 
connection method of the URL class will use the protocol portion of the URL to decide which 
port to connect to. 


Open a connection to the URL 


Once you have a URL object, there are a number of things that you can do with it. One of the 
things you can do with it is to open input and output streams that will be connected to the server 
software that is monitoring the port of interest. 


The code in Listing 6 opens a connection to the URL described by this URL object and returns an 
input stream object for reading data from the connection. This is the point where the port number 
defaults on the basis of the protocol specification in the URL object. 


Listing 6 - Open a connection to the URL. 


BufferedReader htmlPage = 
new BufferedReader(new InputStreamReader ( 
url.openStream())); 


Be aware that only a small portion of the statement in Listing 6 has to do with URL processing. 
The remainder of the statement has to do with the more complex topic of I/O stream processing. 


Read and display the data 


The remaining code in this program, as shown in Listing 7, is completely straightforward. Data 
is read from the stream one line at a time and displayed as it is read. The readLine method 
returns null when there is no more data to be read from the stream and the program terminates. 


Listing 7 - Read and display the data. 


while((dataLine = htmlPage.readLine()) != null){ 
System.out.println(dataLine) ; 
}//end while loop 


Not complicated at all 


As you can see, it is very easy to write a program that will connect to an HTTP server and 
download the contents of a specified file. There are lots of things that you do by using this as a 
starting point. A common assignments given to students is to add a little more knowledge and 
code to this and to write a crawler that will crawl the web searching for some specified file 
contents. 


Run the programs 


I encourage you to copy the code from Listing 8 and Listing 9 Compile the code and execute it. 
Experiment with the code, making changes, and observing the results of your changes. Make 
certain that you can explain why your changes behave as they do. 


What's next? 


The next module in the series will deal with the URLConnection class. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4640: The URL Class and the URLEncoder Class 
e File: Java4640.htm 

e Published: 03/02/14 

e Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to download a PDF file for 
this module at no charge, and also makes it possible for you to purchase a pre-printed version of 
the PDF file, you should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the Connexions website 
even if you purchase the PDF version of the module. 

In the past, unknown individuals have copied my modules from cnx.org, converted them to 
Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither 
receive compensation for those sales nor do I know who does receive compensation. If you 
purchase such a book, please be aware that it is a copy of a module that is freely available on 
cnx.org and that it was made and published without my prior knowledge. 

Affiliation : I am a professor of Computer Information Technology at Austin Community 
College in Austin, TX. 


Complete program listings 


Listing 8 - The program named Java4640a. 


/*File Java4640a.java Copyright 1998, R.G.Baldwin Revised 
01/05/14 


This program exercises four of the constructors and 
six of the methods of the URL class. 


The program also illustrates the use of the URLEncoder 
class to convert a string containing spaces and other 
such characters into UTF-8 format. 


PAI I REL R CR RR, HER GR, ER MERA COR Arte te ame Rea aE a eum ies ee dente cme ded Rea Marae RENN RECA 


import java.net.*; 
import java.io.*; 


Class Java4640a{ 
public static void main(String[] args){ 
Java4640a obj = new Java4640a(); 
tryt 
System.out.printin( 
"Use simple string constructor for host URL"); 
obj .display(new URL("http://www.austincc.edu") ); 


System.out.printin("Use simple string constructor " + 
"for host plus file"); 

obj .display(new URL( 
"http://www.austincc.edu/baldwin") ); 


System.out.printin( 
"Use strings for protocol, host, and file"); 

obj .display(new URL( 
"http", "www.austincc.edu","/baldwin") ); 


System.out.printin("Use strings for protocol " + 
"host, and file\n and int for port"); 
obj .display(new URL( 
"http", "www.austincc.edu",80,"/baldwin") ); 


System.out.printin("Construct absolute URL from " + 
"host URL and relative URL"); 
URL baseURL = new URL( 
"http://www.austincc.edu/baldwin/hello.htm1") ; 
obj .display(new URL(baseURL, "/baldwin/Index.htm1l")); 


System.out.printin("Now use URLEncoder to create " + 
"UTF-8 encoded String"); 
System.out.printin("http://space .tilde~.plus+.com"); 
System.out.println(URLEncoder .encode( 
"http://space .tilde~.plus+.com","UTF-8")); 
}catch(MalformedURLException | 
UnsupportedEncodingException e){ 
e.printStackTrace(); 
}//end catch 


}//end main 
Oe // 


void display(URL url){//method to display parts of URL 


System. 
System. 
System. 
System. 
System. 


out. 
out. 
out. 
out. 
out. 


print(url.getProtocol() + " "); 
print(url.getHost() + " "); 
print(url.getPort() + " "); 
print(url.getFile() + " "); 
println(url.getRef()); 


//Now display entire URL as a string. 
System.out.printin(url.toString()); 
System.out.printin(); 
}//end display 
}//end class 


Java4640a 


Listing 9 - The program named Java4640d. 


Listing 9 - The program named Java4640d. 


/*File Java4640d.java Copyright 1998, R.G.Baldwin Revised 
01/06/14 


Illustrates connecting to a URL and reading a file from 
that URL as an input stream. 


Computer must be online for this program to run properly. 
Otherwise, it will throw an exception of type 


UnknownHostException. 
BRR RR, BERBERS, ROR BERR BRR BRS BRR RRR NR RD, BORO ROR MOM: RID, BOOM, Rigo, Beg 


import java.net.*; 
import java.io.*; 


class Java4640d{ 
public static void main(String[] args){ 
String dataLine; 
tryt 
//Get a URL object 
URL url = new URL( 
"http:/7/www.austincc.edu/baldwin/page1.htm1"); 


//Open a connection to this URL and return an 
// input stream for reading from the connection. 
BufferedReader htmlPage = 
new BufferedReader (new InputStreamReader ( 
url.openStream())); 


//Read and display file one line at a time. 
while((dataLine = htmlPage.readLine()) != null){ 
System.out.println(dataLine) ; 
}//end while loop 
}//end try 
catch(Exception e){ 
e.printStackTrace(); 
}//end catch 


}//end main 
}//end class Java4640d 


-end- 


Java4640r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4640: The URL Class and the URLEncoder Class in the Network 
Programming sub-collection. 


Table of Contents 


e Preface 
e Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INE W 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4640: The URL Class and the URLEncoder Class in the Network 


Programming sub-collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


Java provides at least two different ways to do network programming. The 
two ways are associated with socket classes and URL classes. 


Go to answer 1 


Question 2 
True or False? 
Socket programming occurs at a higher level than URL programming 


Go to answer 2 


Question 3 
True or False? 


An object of the URL class provides a method for extracting each of the 
following parts of a URL: 


¢ protocol used to access the server (such as http), 

e name of the server, 

¢ port on the server (optional) 

e path and name of a specific file on the server (sometimes optional) 
e anchor or reference within the file (optional) 


Go to answer 3 


Question 4 


True or False? 


The URLEncoder class is provided to help deal with problems arising from 
spaces, special characters, non-alphanumeric characters, etc. , that some 
operating systems may allow in file names but which may not be allowed in 
a URL. 


Go to answer 4 


Question 5 
True or False? 


Once you have a URL object connected to a server, you can open input and 
output streams that will be connected to the server software that is 
monitoring the port of interest. 


Go to answer 5 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


Ea None ele 
Display your name here 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


ProbO05a.jpg 
Put your name here 


Answers 


Answer 5 
True. 


Go back to Question 5 


Answer 4 


True. 


Go back to Question 4 


Answer 3 


True. 


Go back to Question 3 


Answer 2 


False. URL programming occurs at a higher level than socket 
programming. 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4640r-Review 
e File: Java4640r.htm 

Published: 03/08/14 

Revised 12/26/14 


Note: Disclaimers: 


Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4650: The URLConnection Class 
This module shows how to use the URLConnection class. 


Table of Contents 
e Preface 
o Viewing tip 


= Figures 
» Listings 


¢ General background information 
e Discussion and sample code 

e Run the program 

e What's next? 

e¢ Miscellaneous 

* Complete program listing 


Preface 


This module is one in a collection of modules designed for teaching INEW 2338 Advanced Java 
(Web) at Austin Community College in Austin, TX. More specifically, it is one in a sub- 
collection of modules designed for teaching network programming in that course. The purpose of 
this module is to introduce the student to the URLConnection class. 


Viewing tip 


I recommend that you open another copy of this module in a separate browser window and use 
the following links to easily find and view the Figures and Listings while you are reading about 
them. 


Figures 


e Figure 1. Partial program output. 


Listings 


e Listing 1. Beginning of the program. 

e Listing 2.. Get a URLConnection object. 

e Listing 3. Get information about the URL. 
e Listing 4. The program named Java4650a. 


General background information 


I don't plan to say very much about the URLConnection class. It is an abstract class that can be 
extended , and it has a protected constructor that takes a URL object as a parameter. 


It has variables or fields that contain useful information about a connection. 


It has many methods that can be used to examine and manipulate an object of the class in a 
variety of different ways. 


If you plan to use the URL class for the higher-lever capabilities that it offers, and you plan to 
write content handlers and protocol handlers , you will probably need to become very familiar 
with this class. In that case, you will probably want to get a copy of a good Java networking 
book, such as Java Network Programming , by Elliotte Rusty Howard, and study the use of this 
class in depth. 


My objective here is simply to make you aware of the existence of the class and its many 
methods, and to provide some examples of how you can get and use an object of the class to 
obtain higher-level information about a connection. 


Discussion and sample code 
This program illustrates connecting to a URL and creating a URLConnection object. 


The program uses the URLConnection object to obtain and display some of the "higher level" 
information about the UR L: 


e the URL 
e the date last modified 
e the content type 


The computer must be online for this program to run properly. Otherwise, it will throw an 
exception of type UnknownHostException . 


Partial program output 
Figure 1 shows part of the output from the program. The first three lines of output correspond to 


the items in the above list, and are the items that we will be primarily interested in for this 
module. 


Figure 1 - Partial program output. 


Figure 1 - Partial program output. 


http://www. austincc.edu/baldwin/page1.html 

Tue Apr 17 23:16:17 CDT 2001 

text/html; charset=iso-8859-1 

<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> 
<html> 

<head> 

<meta http-equiv="Content-Type" content="text/html; 
charset=iso-8859-1"> 

<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; I) 
[Netscape]"> 

<title>Java and JavaScript Programming, by Richard G 
Baldwin</title> 

</head> 

<body bgcolor="#FFFFFF" link="#0000FF" vlink="#FFOQ000" 
lang="EN-US"> 


<hi> 

Baldwin's Test Page 1</h1> 

Click <a 
href="http://www2.austin.cc.tx.us/baldwin/page2.htm1">here</a> 
to view page 2 

<p>Note: The material on this page is not intended to be of 
any particular 


value. This file is posted for the purpose of testing HTTP 
network 

programs only. 

<p>The following red bar is a centered gif file. 

<center> 

<p><img SRC="red_thick_line_1.gif" BORDER=0 id="_x0000_11025" 
height=9 width=300 

></center> 


The program named Java4650a 


I will explain this program in fragments. A complete listing of the program is provided in Listing 
4. 


The URLConnection class is abstract , and therefore cannot be instantiated directly. However, it 
can be extended , and it has a protected constructor that requires a URL object as a parameter. 


A common way to get a URLConnection object is to call a method on a URL object that returns 
an object of a subclass of the URLConnection class. That is the case in the sample program for 
this module. 

I will ignore the exception handling code in the discussion of this program. 

All of the code in the sample program is contained in the main method of the controlling class. 


Beginning of the program 


The beginning of the program and the beginning of the main method is shown in Listing 1 . 


Listing 1 - Beginning of the program. 


import java.net.*; 
import java.io.*; 
import java.util.*; 


class Java4650a{ 
public static void main(String[] args){ 
String dataLine; 
try{ 
//Get a URL object 
URL url = new URL( 
"http://www.austincc.edu/baldwin/pagei.htm1"); 


Get a URL object 


The code at the bottom of Listing 1 instantiates a URL object. This is essentially the same code 
that you saw in an earlier module, but you need to see it again here in order to understand the 
code that follows it. 


URLConnection object 


The code in Listing 2 gets a URLConnection object by calling the openConnection method on 
the URL object instantiated earlier. 


Listing 2 - Get a URLConnection object. 


URLConnection urlConnection = url.openConnection(); 


Get information about the URL 


The code in Listing 3 calls three methods on the URLConnection object to obtain three of the 
higher-level informational aspects of the URL: 


e the URL 
e the date that the file was last modified 
e the content type of the file 


Listing 3 - Get information about the URL. 


System.out.println(urlConnection.getURL()); 

Date lastModified = new Date( 
urlConnection.getLastModified()); 

System.out.println(lastModified); 

System.out.println(urlConnection.getContentType()); 


The result of these three inquiries is shown as the first three lines of text in Figure 1. 
The remaining code 
Following this, the program uses the URL object to get an input stream and to display the 


contents of the file. However, this essentially duplicates a portion of the program in an earlier 
module, so I won't discuss it further here. 


Run the program 
I encourage you to copy the code from Listing 4.. Compile the code and execute it. Experiment 


with the code, making changes, and observing the results of your changes. Make certain that you 
can explain why your changes behave as they do. 


What's next? 


In the next module, I will show you how to download a simple HTML file and to render it ina 
way that is similar to how it would be rendered in a browser. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4650: The URLConnection Class 
e File: Java4650.htm 

e Published: 03/02/14 

e Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to download a PDF file for 
this module at no charge, and also makes it possible for you to purchase a pre-printed version of 
the PDF file, you should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the Connexions website 
even if you purchase the PDF version of the module. 

In the past, unknown individuals have copied my modules from cnx.org, converted them to 
Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither 
receive compensation for those sales nor do I know who does receive compensation. If you 
purchase such a book, please be aware that it is a copy of a module that is freely available on 
cnx.org and that it was made and published without my prior knowledge. 

Affiliation : | am a professor of Computer Information Technology at Austin Community 
College in Austin, TX. 


Complete program listing 

Listing 4 - The program named Java4650a. 

/*File Java4650a.java Copyright 1998, R.G.Baldwin 
Revised 01/05/14 


Illustrates connecting to a URL and creating a 
URLConnection object. 


Uses the URL object to obtain and display 


the URL, the date last modified, and the content type. 


Also uses the URLConnection object to obtain an 
input stream object. Then uses this object to read and 
display the file. 


BRO BEB, RR RR, RB, BRB ROR RRR, BOM, BR, RON R, BRR, RM, BRR, BON MBAR, BNR Bee Bee 


import java.net.*; 
import java.io.*; 
import java.util.*; 


class Java4650a{ 
public static void main(String[] args){ 
String dataLine; 
try{ 
//Get a URL object 
URL url = new URL( 
"http://www.austincc.edu/baldwin/page1.htm1") ; 


//Open a connection to the URL and get a 
// URLConnection object. 
URLConnection urlConnection = url.openConnection(); 


//Use the connection to get and display the URL 
System.out.println(urlConnection.getURL()); 


//Use the connection to get and display the date last 

// modified. 

Date lastModified = new Date( 
urlConnection.getLastModified()); 

System.out.printin(lastModified); 


//Use the connection to get and display the content 
// type. 
System.out.println(urlConnection.getContentType()); 


//Use the connection to get an InputStream object. 
// Use the InputStream object to instantiate a 
// DataInputStream object. 
BufferedReader htmlPage = 
new BufferedReader(new InputStreamReader ( 
url.openStream())); 


//Use the DataInputStream object to read and display 

// the file one line at a time. 

while((dataLine = htmlPage.readLine()) != null){ 
System.out.printin(dataLine) ; 

}//end while loop 


}//end try 
catch(Exception e){ 

e.printStackTrace(); 
}//end catch 


}//end main 
}//end class Java4650a 


-end- 


Java4650r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4650: The URLConnection Class in the Network Programming 
sub-collection. 


Table of Contents 


e Preface 
e Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4650: The URLConnection Class in the Network Programming 


sub-collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


The URLConnection class is an abstract class that can be extended . It has 
a protected constructor that takes a URL object as a parameter. 


Go to answer 1 


Question 2 
True or False? 
The URLConnection class can be instantiated directly. 


Go to answer 2 


Question 3 
True or False? 


A common way to get a URLConnection object is to call a method ona 
URL object that returns an object of a subclass of the URLConnection 
class. 


Go to answer 3 


Question 4 
True or False? 


The method named openConnection can be called on a URL object to get 
a reference to an object of a class that is a subclass of the URLConnection 
class. 


Go to answer 4 


Question 5 
True or False? 


Three methods can be called on a URLConnection object to obtain the 
following three informational aspects of the URL: 


e the URL 
e the date that the file was last modified 
e the content type of the file 


Go to answer 5 
What is the meaning of the following two images? 
These images were inserted here simply to insert some space between the 


questions and the answers to keep them from being visible on the screen at 
the same time. 


Ea None . Lox] 
Display your nametheke 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 5 
True. 


Go back to Question 5 


Answer 4 
True. 


Go back to Question 4 


Answer 3 
True. 


Go back to Question 3 


Answer 2 


False. The URLConnection class is abstract , and therefore cannot be 
instantiated directly. However, it can be extended , and it has a protected 
constructor that requires a URL object as a parameter. 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4650r-Review 
File: Java4650r.htm 

e Published: 03/08/14 

Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 


I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4655: A Rendering Web Browser 
The purpose of this module is to show students how to use Java Swing to render a 
web page in a JFrame object. 


Table of Contents 


Preface 


o Viewing tip 


=» Figures 
» Listings 


e Discussion and sample code 


A skeleton program - Java4655c 
The program named Java4655b 
The program named Java4655a 
What's missing? 


Oo Oo 0 0 


e Run the program 

e What's next? 

e Miscellaneous 

¢ Complete program listing 


Preface 


This module is one in a collection of modules designed for teaching INEW 2338 
Advanced Java (Web) at Austin Community College in Austin, TX. More 
specifically, it is one in a sub-collection of modules designed for teaching network 
programming in that course. The purpose of this module is to show students how 
to use Java Swing to render a web page in a JFrame object. 


Viewing tip 


I recommend that you open another copy of this module in a separate browser 
window and use the following links to easily find and view the Figures and 
Listings while you are reading about them. 


Figures 


Figure 1. JFrame output from the program named Java4655c. 
Figure 2. Command line output from the program named Java4655c. 
Figure 3. JFrame output from the program named Java4655b. 
Figure 4. JFrame output from the program named Java4655a. 


Listings 


Listing 1. Beginning of the program named Java4655c. 

Listing 2. The method named runner. 

Listing 3. Beginning of the class named Java4655cHtmlHandler. 
Listing 4. Open the URL object in a JEditorPane object. 
Listing 5. Register a hyperlink listener. 

Listing 6. Display the JEditorPane. 

Listing 7. The hyperlinkUpdate method. 

Listing 8 . The constructor for the Java4655bHtmlHandler class. 
Listing 9. The HyperlinkEvent handler for Java4655b. 

Listing 10. Scrolling code in Java4655a. 

Listing 11. The program named Java4655c. 

Listing 12. The program named Java4655b. 

Listing 13. The program named Java4655a. 


Discussion and sample code 


In an earlier module, you learned how to connect to a website and cause a raw text 
version of a file to be downloaded and displayed. However, the display of raw 
HTML text isn't very useful, which is why rendering web browsers were invented. 


In this module, you will learn how to connect to a website and cause an HTML 
file to be downloaded and rendered in a JFrame object. We will develop a 
program that makes it possible to follow hyperlinks much as you would expect 
with a commercial web browser. 


A skeleton program - Java4655c 


I will begin this explanation with a skeleton program that illustrates four important 
aspects of rendering a webpage in a Swing JFrame object : 


e Getting a URL object that is connected to a webpage. 
e Opening the URL object in a JEditorPane object. 

e Displaying the JEditorPane in a rendered format. 

e Handling hyperlink events on the JEditorPane . 


(Note that there are alternatives to the first two items in the above list, which we 
will see later.) 


To keep the code simple, two important aspects of webpage rendering will be 
omitted from this program: 


e Scrolling large web pages. 
e Following hyperlinks. 


These capabilities will be added to other programs later in this module. 
Beginning of the program named Java4655c 


I will explain this program in fragments. A complete listing of the program is 
provided in Listing 11 . 


Listing 1 shows the beginning of the program. 


Listing 1 - Beginning of the program named Java4655c. 


Listing 1 - Beginning of the program named Java4655c. 


import javax.swing.*; 

import javax.swing.event.*; 
import javax.swing.text.html.*; 
import java.net.*; 

import java.awt.*; 

class Java4655c{ 


public static void main(String[] args) { 
new Java4655c().runner( 


"http: //www.austincc.edu/baldwin" ); 
}//end main 


There is nothing new in Listing 1. This code simply calls a method named runner 
passing a string description of a URL as a parameter. 


The method named runner 


The method named runner is shown in Listing 2 . 


Listing 2 - The method named runner. 


Listing 2 - The method named runner. 


void runner(String webSiteLink) { 
try{ 
//Create a new URL object from the website 
string 
URL website = new URL(webSiteLink); 
//Instantiate an overall web page handler 
new Java4655cHtmlHandler(website) ; 
}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end runner 
}//end class Java4655c 


Listing 2 begins by getting a URL object that is connected to the specified 
webpage to satisfy the first item in the above list . 


Then Listing 2 instantiates a new object of the class named 


Java4655cHtmlHandler passing the URL object's reference as a parameter to the 


constructor. From this point forward, the behavior of the program will be 
controlled by the object of the Java4655cHtmlHandler class. 


Listing 2 also signals the end of the class named Java4655c . 


Beginning of the class named Java4655cHtmlHandler 


The beginning of the class named Java4655cHtmlHandler and the beginning of 


the constructor for that class is shown in Listing 3 


Listing 3 - Beginning of the class named Java4655cHtmlHandler. 


Listing 3 - Beginning of the class named Java4655cHtmlHandler. 


class Java4655cHtmlHandler extends JFrame 
implements 
HyperlinkListener { 
//Constructor 
public Java4655cHtmlHandler(URL website) { 
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); 
setTitle("Copyright 2014, R.G.Baldwin"); 


There is nothing new or unusual in Listing 3 with the possible exception of the 
fact that the class implements the interface named HyperlinkListener . This has 
two important ramifications: 


e The class must provide concrete implementations of all the methods declared 
in the interface. 

e An object of the class can serve as a listener for events of type 
HyperlinkEvent . 


As you will see later, the HyperlinkListener interface declares only one method 
and it is named hyperlinkUpdate . The method receives one incoming parameter 
of type HyperlinkEvent . 


The hyperlinkUpdate method 


The documentation for the hyperlinkUpdate method is rather sparse, stating only 
that the method is "Called when a hypertext link is updated" and that the incoming 
parameter represents "the event responsible for the update." 


As you will see later, an event occurs whenever the user touches a hyperlink in the 
webpage with the mouse. The HyperlinkEvent object encapsulates information 
identifying the event as being one of the following types: 


e ENTERED 
e EXITED 
e ACTIVATED 


I will pursue the three types of hyperlink events in more detail later. 


Open the URL object in a JEditorPane object 


Listing 4 opens the URL object in a JEditorPane object to satisfy the second item 
in the above list. 


(I will ignore the exception handling code while explaining this 
program.) 


Listing 4 - Open the URL object in a JEditorPane object. 


try{ 
if(website != null) { 
//Create a JEditorPane containing the web 
page. 
JEditorPane html = new 
JEditorPane(website); 
html.setEditable( false) ; 


Fortunately, the online documentation for the JEditorPane is fairly detailed. I will 
refer you to that documentation for more information. 


The JEditorPane constructor 
Listing 4 calls an overloaded JEditorPane constructor that is described in the 


documentation as follows: 


"Creates a JEditorPane based on a specified URL for input." 


( Note that there is another constructor that would allow us to create the 
JEditorPane object passing a URL string to the constructor. Had I used that 


constructor, it wouldn't have been necessary to create the URL object. For 
illustration, I will use that constructor in a later program in this module.) 


Documentation snippets 


There are a couple of snippets from that documentation that are particularly 
important to this module. The first snippet is: 


"Some kinds of content may provide hyperlink support by generating 
hyperlink events. The HTML EditorKit will generate hyperlink events if 
the JEditorPane is not editable (JEditorPane.setEditable(false); has been 
called)." 


Since we are definitely interested in hyperlink events, Listing 4 calls the 
setEditable method on the new JEditorPane object passing false as a parameter. 


A second snippet that will be important later in this module reads: 


"The setPage method can be used to initialize the component from a 
URL." 


We will use this capability later to cause a hyperlink event handler to follow a link 
in a webpage when we click on the hyperlink. 


Register a hyperlink listener 
Listing 5 uses standard Java event handling code to register a hyperlink listener 


object on the JEditorPane object. As I mentioned earlier, this object is suitable 
for use as a listener object. 


Listing 5 - Register a hyperlink listener. 


Listing 5 - Register a hyperlink listener. 


html.addHyperlinkListener(this); 


I will explain the hyperlink listener code shortly. 
Display the JEditorPane 


Listing 6 uses standard Swing code to display the JEditorPane in a JFrame 
object. There is nothing new or interesting about this code so I won't discuss it 
further. 


Listing 6 - Display the JEditorPane. 


this.getContentPane().add(html); 
this.setSize(669, 669); 
this.setVisible(true); 

}//end if 


}catch(Exception e)f{ 
e.printStackTrace(); 


}//end catch 
}//end constructor 


Listing 6 also signals the end of the constructor for the class named 
Java4655cHtmlHandler . 


The event handler method 


Listing 7 shows the event handler method named hyperlinkUpdate in its entirety. 


Listing 7 - The hyperlinkUpdate method. 


public void hyperlinkUpdate(HyperlinkEvent e) { 
if (e.getEventType() == 


HyperlinkEvent.EventType. ENTERED) { 
System.out.println("ENTERED"); 
telse if (e.getEventType() == 


HyperlinkEvent.EventType.EXITED) { 
System.out.println( "EXITED" ); 
}else if (e.getEventType() == 


HyperlinkEvent.EventType.ACTIVATED) { 
System.out.println("ACTIVATED"); 
}//end if 
}//end hyperlinkUpdate method 
| [----------- 2-2-2 enn r ee ee eee eee ---e 


}//end class Java4655cHtmlHandler 


This hyperlink event handler simply displays the type of event on the command- 
line screen as the mouse pointer touches hyperlinks on the webpage. The possible 
types of events and the actions that cause them are as follows: 


e ENTERED - touch a hyperlink with the mouse 
e EXITED - move the mouse pointer away from a touched hyperlink 
e ACTIVATED - click a hyperlink with the mouse 


The code in Listing 7 is straightforward and shouldn't require further explanation. 


Listing 7 also signals the end of the class named Java4655cHtmlHandler . 
The program output 


Figure 1 shows the output that you should see if you compile and run this 
program. Note however that the content of this page changes each semester so you 


may see something a little different. 


Figure 1 - JFrame output from the program named Java4655c. 


E43 copyright 2014, R.G.Baldwin 


Baldwin's Austin Community College Course Link Page 
Miscellaneous Links 


e Baldwin's e-book titled Object-Onented Programming (OOP) with Java. 

« Baldwin's e-book titled Mathematical Applications for Game Development. 
e Baldwin's e-book titled Anatomy of a Game Engine. 

e Baldwin's Programming Oldies but Goodies. 

« Baldwin's Supplemental Online Instructional Materials. 

e Baldwin's Programming with XNA Game Studio. 

e Blackboard login page. 


All students enrolled in courses taught by Prof. Baldwin are required to complete 
online orientation at the beginning of the course. Follow the link to the Main page for 
your course below to complete online orientation. 


Then log into Blackboard, access your course, and use the Blackboard "Send Email” 
feature within the first five days of the course to send an Email message to Prof. 
Baldwin confirming that you have completed online orientation. Make the subject of 
your message read "Online orientation complete." If you fail to do this, you may suffer 
administrative penalties, which may include the loss of eligibility for financial aid. 


Spring 2014 


As I mentioned earlier, this program doesn't allow scrolling for web pages that are 
too large to fit in the JEditorPane . As you can see in Figure 1 , the webpage 
simply spills outside the viewing area. We will deal with that later in this module. 


This program also doesn't support link following. If you touch or click a link, the 


code in Listing 7 simply reports that fact on the command line screen. We will also 
deal with that later in this module. 


Figure 2 shows the result of moving the mouse around inside the hyperlinks in 
Figure 1 and finally clicking on one of those links to create an ACTIVATED event. 


Figure 2 - Command line output from the program named Java4655c. 


Gi M:\Program Files\JCreator LE\GE2001.exe : 


Now that you know the basics, we can put some meat on the skeleton. 


The program named Java4655b 


This program is similar to the previous program except that it allows you to follow 
hyperlinks. However, I will continue to defer scrolling until later in the module. 


Once again, I will explain this program in fragments. However, rather than to 
explain the complete program, I will explain only those things that are 
significantly different from the previous program. 


A complete listing of the program is provided in Listing 12 . 
The constructor for the Java4655bHtmlHandler class 


Listing 8 shows the beginning of the Java4655bHtmlHandler class including the 
entire constructor. 


Listing 8 - The constructor for the Java4655bHtmlHandler class. 


Class Java4655bHtmlHandler extends JFrame 
implements 
HyperlinkListener { 
JEditorPane html; 


//Constructor 
public Java4655bHtmlHandler(String websiteString) 


setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) ; 
setTitle("Copyright 2014, R.G.Baldwin"); 


try{ 
if(websiteString != null) { 
html = new JEditorPane(websiteString); 
html.setEditable( false) ; 
html.addHyperlinkListener(this); 


this.getContentPane( ).add(html, BorderLayout.CENTER); 
this.setSize(669, 669); 
this.setVisible(true); 
}//end if 


}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end constructor 


Differences from the previous program 


One difference between the code in Listing 8 and the corresponding code in the 
previous program is that this version requires the website to be specified as a 
String instead of a URL . 


Another difference is that this version declares the JEditorPane reference as an 
instance variable to make it accessible to the HyperlinkEvent handler discussed 


below. 
The HyperlinkEvent handler 


Listing 9 shows the HyperlinkEvent handler in its entirety. 


Listing 9 - The HyperlinkEvent handler for Java4655b. 


public void hyperlinkUpdate(HyperlinkEvent e) { 
if (e.getEventType() == 


HyperlinkEvent.EventType.ACTIVATED) { 
//Tgnore ENTERED and EXITED events and 
process only 
// ACTIVATED events. 
if (e instanceof HTMLFrameHyperlinkEvent) { 
//Tgnore events in HTML frames 
System. out. println( 
"HTML Frame events are 
ignored"); 
} else { 
try 7 
//Display page defined by the 
HyperlinkEvent. 
html.setPage(e.getURL()); 
} catch (Exception ex) { 
ex.printStackTrace(); 
}//end catch 
}//end else 
}//end if 
}//end hyperlinkUpdate method 


This code makes it possible to follow links by clicking the hyperlinks in the 
HTML page that is displayed. Note that only ACTIVATED events are processed 


and even those events are not processed if they are contained in an HTML frame. 
Following links 


The code in Listing 9 is straightforward. The statement that causes the program to 
follow links is the call to the setPage method passing a URL as a parameter. The 
documentation for this message reads "Sets the current URL being displayed." 


The URL to be displayed is obtained by calling the getURL method on the 
incoming HyperlinkEvent object. The documentation for this method simply 
reads "Gets the URL that the link refers to." 


As you can see, therefore, writing a simple browser that will access a web page 
and follow links is not difficult. The output from running this program is shown in 
Figure 3. 


Figure 3 - JFrame output from the program named Java4655b. 


sll x 


E4 copyright 2014, R.G.Baldwin 
?xml version="1.0" encoding="1so-8859-1"7> 


Richard G Baldwin Programming Tutorials 


Baldwin@DickBaldwin.com 
http:/iwww.dickbaldwin.com 


If you find the links to any of my tutorials broken, you might try either: 


1. Going to Google or Bing and searching the web for pages having the same 
title, or 

2. Going to More articles by Richard G. Baldwin at Developer.com and 
searching that page for the tutorial by title. 


One of those two options is almost certain to lead you to a copy of the tutorial. 


If you are looking for the drawing program for the blind that you may have heard about, it is posted at: 
http-//www_austincc_edu/baldwin/SWT-SVG/SVGDraw01 zip and is available for immediate download. - 
09/23/11 


This web site contains more than 600 programming tutorial lessons that | have published on 
ActionScript, Flex, Alice, Java, JavaScript, Python, XML, C#, Digital Signal Processing, and Wireless 
Technology. 


These tutorial lessons are freely available for online viewing. 


Scrolling 


You should be able to run the program and follow the links from one page to the 
next. We are still missing something, however. If you click on a link to an anchor 
that is on the same page but not visible in the JFrame , nothing happens. This is 
because this version of the program is incapable of scrolling to and displaying that 
location on the page. Our next task will be to correct that issue. 


The program named Java4655a 


Scrolling code in Java4655a 


Listing 13 provides a complete listing of a program that incorporates scrolling. 
The only difference between this program and the previous program is shown in 
Listing 10 . 


Listing 10 - Scrolling code in Java4655a. 


if(websiteString != null) { 
html = new JEditorPane(websiteString); 
html.setEditable( false) ; 
html.addHyperlinkListener(this); 


JScrollPane scroller = new JScrollPane(); 
JViewport vp = scroller.getViewport(); 
vp.add(htm1); 

this.getContentPane().add( 


scroller,BorderLayout.CENTER) ; 
this.setSize(669, 669); 
this.setVisible(true); 

}//end if 


The code in Listing 10 that provides scrolling has nothing to do with network 
programming so I will leave it up to the student to find an explanation of this code 
somewhere else on the web. 


Figure 4 shows the initial output from running this program. Note the vertical 
scroll bar on the right side of the image. 


Figure 4 - JFrame output from the program named Java4655a. 


E4 copyright 2014, R.G.Baldwin 


?xml version="1.0" encoding="1so-8859-1"7> 


Richard G Baldwin Programming Tutorials 


Baldwin@DickBaldwin.com 
hittp:/iwww.dickbaldwin.com 


If you find the links to any of my tutorials broken, you might try either: 


1. Going to Google or Bing and searching the web for pages having the 
same title, or 

2. Going to More articles by Richard G. Baldwin at Developer.com and 
searching that page for the tutorial by title. 


One of those two options is almost certain to lead you to a copy of the tutorial. 


lf you are looking for the drawing program for the blind that you may have heard about, it is posted 
at: http-//www_austincce edu/baldwin/SWT-SVG/SVGDraw01 zip and is available for immediate 
download. - 09/23/11 


This web site contains more than 600 programming tutorial lessons that | have published on 
ActionScript, Flex, Alice, Java, JavaScript, Python, XML, C#, Digital Signal Processing, and Wireless 
Technology. 


These tutorial lessons are freely available for online viewing. 


What's missing? 


There are at least three features that we would need to add to turn this program 
into a simple but functional web browser. 


e A way for the user to enter the website of interest and to change it at will. 
e A "Back" button. 
e¢ A "Forward" button. 


Adding these features is not particularly difficult, but I will leave it as an exercise 
for the student to add these features and convert this program into a functional web 
browser. 


Run the program 


I encourage you to copy the code from Listing 11, Listing 12 , and Listing 13. 
Compile the code and execute it. Experiment with the code, making changes, and 
observing the results of your changes. Make certain that you can explain why your 
changes behave as they do. 


What's next? 


The next module will introduce sockets for network programming. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4655: A Rendering Web Browser 
e File: Java4655.htm 

e Published: 03/02/14 

e Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to download a 
PDF file for this module at no charge, and also makes it possible for you to 
purchase a pre-printed version of the PDF file, you should be aware that some of 
the HTML elements in this module may not translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 

In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 


showing me as the author. I neither receive compensation for those sales nor do I 
know who does receive compensation. If you purchase such a book, please be 
aware that it is a copy of a module that is freely available on cnx.org and that it 
was made and published without my prior knowledge. 

Affiliation : | am a professor of Computer Information Technology at Austin 
Community College in Austin, TX. 


Complete program listing 


Listing 11 - The program named Java4655c. 


/*File Java4655c.java 
Copyright 2014, R.G.Baldwin 
Rev 01/07/14 


This is a skeleton program that illustrates how to load 
a web page into a JEditorPane and illustrates how to 
identify the three types of hyperlink events: 


ENTERED 
EXITED 
ACTIVATED 


KREKEKKEKEKEKKKEKRKEKEKKEKE RK KEKEKRKKE KEKE KKK KK KEKKKE KK KRKKKE KKK KKKKE KEKE 


xx * / 


import javax.Swing.*; 

import javax.Swing.event.*; 
import javax.swing.text.html.*; 
import java.net.*; 

import java.awt.*; 


class Java4655c{ 


public static void main(String[] args){ 
new Java4655c().runner( 


"http: //www.austincc.edu/baldwin"); 
}//end main 


void runner(String webSiteLink) { 
try{ 
//Create a new URL object from the website string 
URL website = new URL(webSiteLink); 
//Instantiate an overall web page handler 
new Java4655cHtmlHandler(website) ; 
}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end runner 
}//end class Java4655c 


f fra Sa a sa SS ae aS Sa SS SS SS SSS Sa SS SSS 
==// 
class Java4655cHtmlHandler extends JFrame 
implements 
HyperlinkListener{ 
//Constructor 


public Java4655cHtmlHandler(URL website) { 
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); 


setTitle("Copyright 2014, R.G.Baldwin"); 


try{ 
if(website != null) { 


//Create a JEditorPane containing the web page. 
JEditorPane html = new JEditorPane(website); 
html.setEditable(false); 


//Register a listener to listen for hyperlink 
// events. 
html.addHyperlinkListener(this); 


//Display the JEditorPane 
this.getContentPane().add(html); 
this.setSize(669, 669); 


this.setVisible(true); 
}//end if 


}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end constructor 
[/------- 2-2-2 rn rrr re ee re ree eee eee 


//This hyperlink event listener simply displays the 
// type of event on the command-line screen. 
public void hyperlinkUpdate(HyperlinkEvent e) { 

if (e.getEventType() == 


HyperlinkEvent .EventType. ENTERED) { 
System.out.println("ENTERED"); 
selse if (e.getEventType() == 


HyperlinkEvent .EventType.EXITED) { 
System.out.println( "EXITED" ); 
}else if (e.getEventType() == 


HyperlinkEvent .EventType.ACTIVATED) { 


System.out.println("ACTIVATED"); 
}//end if 


}//end class Java4655cHtmlHandler 


Listing 12 - The program named Java4655b. 


/*File Java4655b.java 
Copyright 2014, R.G.Baldwin 
Rev 01/05/14 


This is a simple web browser that can follow links. 
Uses website string to create JEditPane object. 


Ignores ENTERED and EXITED hyperlink events. Uses 
ACTIVATED events to follow links. 


Ignores links in HTML frames. 


KKEKEKKKKEKKKRKRKEKEKRKREKR KERR KKK KEKE KRKRKKE KEKE KEKKKE KK KKK KKK KKKKEKEKKKKEESE 


a 


import javax.swing.*; 

import javax.swing.event.*; 
import javax.swing.text.html.*; 
import java.net.*; 

import java.awt.*; 


Class Java4655b{ 
public static void main(String[] args){ 
new 
Java4655b().runner("http://www.dickbaldwin.com") ; 
}//end main 


void runner(String websiteString) { 
try{ 
//Pass the website string to the constructor 
new Java4655bHtmlHandler(websiteString); 
}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end runner 
}//end class Java4655b 


//This version of the website handler requires the 
website 
// to be specified as a String instead of a URL. 


Class Java4655bHtmlHandler extends JFrame 
implements 
HyperlinkListener{ 
JEditorPane html; 


//Constructor 

public Java4655bHtmlHandler(String websiteString) { 
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) ; 
setTitle("Copyright 2014, R.G.Baldwin"); 


try{ 
if(websiteString != null) { 
html = new JEditorPane(websiteString); 
html.setEditable( false) ; 
html.addHyperlinkListener(this); 


this.getContentPane().add(html, BorderLayout.CENTER); 
this.setSize(669, 669); 
this.setVisible(true); 
}//end if 


}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end constructor 
[/------- 2-2-2 nner rrr rr ee er ee eee eee 


public void hyperlinkUpdate(HyperlinkEvent e) { 
if (e.getEventType() == 


HyperlinkEvent.EventType.ACTIVATED) { 
//Tgnore ENTERED and EXITED events and process 
only 
// ACTIVATED events. 
if (e instanceof HTMLFrameHyperlinkEvent) { 
//Tgnore events in HTML frames 
System.out.println( 
"HTML Frame events are 


ignored"); 
} else { 
try 
//Display page defined by the HyperlinkEvent. 
html.setPage(e.getURL()); 
} catch (Exception ex) { 
ex.printStackTrace(); 
}//end catch 
}//end else 
}//end if 


Sy apache as lean eaten yas May Shea sagen teieh a th Dat 8 De eaten a iene hin 


}//end class Java4655bHtmlHandler 


Listing 13 - The program named Java4655a. 


/*File Java4655a.java 
Copyright 2014, R.G.Baldwin 
Rev 01/05/14 


This is a simple web browser that can follow 
links. 


It ignores links in HTML frames. 


KKEKEKKKKEKKKEKRKRKEKKKE RK KEKEKRKE KEKE KRKKK KEKE KKK KEKE KEKKRKE KKK KKKKEKKEKKKESE 


x * / 


import javax.Swing.*; 

import javax.swing.event.*; 
import javax.swing.text.html.*; 
import java.net.*; 

import java.awt.’*; 


class Java4655a{ 
public static void main(String[] args){ 
new 
Java4655a().runner("http://www.dickbaldwin.com") ; 


}//end main 


void runner(String websiteString) { 
try{ 
new Java4655aHtmlHandler(websiteString); 
}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end runner 
}//end class Java4655a 


class Java4655aHtmlHandler extends JFrame 
implements 
HyperlinkListener{ 
JEditorPane html; 


//Constructor 

public Java4655aHtmlHandler(String websiteString) { 
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); 
setTitle("Copyright 2014, R.G.Baldwin"); 


try{ 
if(websiteString != null) { 
html = new JEditorPane(websiteString); 
html.setEditable( false) ; 
html.addHyperlinkListener(this); 


JScrollPane scroller = new JScrollPane(); 
JViewport vp = scroller.getViewport(); 
vp.add(htm1); 

this.getContentPane().add( 


scroller, BorderLayout.CENTER) ; 
this.setSize(669, 669); 
this.setVisible(true); 

}//end if 


}catch(Exception e){ 
e.printStackTrace(); 
}//end catch 
}//end constructor 


public void hyperlinkUpdate(HyperlinkEvent e) { 
if (e.getEventType() == 


HyperlinkEvent.EventType.ACTIVATED) { 
//Tgnore ENTERED and EXITED events and process 
only 
// ACTIVATED events. 
if (e instanceof HTMLFrameHyperlinkEvent) { 
//TIgnore events in HTML frames 
System.out.println( 
"HTML Frame events are 
ignored"); 
} else { 


try { 
//Display page defined by the HyperlinkEvent. 


html.setPage(e.getURL()); 
} catch (Exception ex) { 
ex.printStackTrace(); 
}//end catch 
}//end else 
}//end if 
}//end hyperlinkUpdate method 
[[--------- 2-2-2 ne nn nner ree eee ee eee ---e 


}//end class Java4655aHtmlHandler 


-end- 


Java4660: Sockets 
The purpose of this module is to introduce the student to the Socket class. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


Simple TCP/IP services 
Echo program 

Date/time program 
Simple browser program 


o Oo 0 O 


e Run the programs 
e Miscellaneous 
¢ Complete program listings 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
More specifically, it is one in a sub-collection of modules designed for 
teaching network programming in that course. The purpose of this module 
is to introduce the student to the Socket class. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 


Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Successful daytime query. 

e Figure 2. Output for a successful echo test. 

e Figure 3. Daytime program output. 

e Figure 4. Output from the simple browser program. 


Listings 


e Listing 1. Beginning of the program named Java4660a. 
e Listing 2 . Instantiate a Socket object. 

e Listing 3. Get I/O stream objects. 

e Listing 4. Send a line of text to the server and display the echo. 
e Listing 5. Beginning of the program named Java4660b. 
e Listing 6. Get an input stream. 

e Listing 7. Read and display incoming data. 

e Listing 8. Beginning of the program named Java4660c. 
e Listing 9. Create input and output streams. 

e Listing 10. Send a GET command. 

e Listing 11. Read and display text from the server. 

e Listing 12. The program named Java4660a. 

e Listing 13. The program named Java4660b. 

e Listing 14. The program named Java4660c. 


General background information 


Sockets in Java come in at least three varieties that are implemented by the 
following Java classes 


e Socket 
¢ DatagramSocket 
e ServerSocket 


The first two socket classes represent TCP and UDP communications 
respectively. 


Generally, these two socket classes are used to implement both clients and 
servers, while the ServerSocket class is only used to implement servers. 


This module will concentrate on the use of the Socket class. The 
DatagramSocket class will be covered a future module. In the meantime, 
you can read about the DatagramSocket class and other interesting topics 
in my earlier publications at: 


Network Programming - Server Sockets 

¢ Network Programming - Datagram Clients 

e Network Programming - Datagram Servers 

e Network Programming - Stubs, Skeletons, and Remote Objects 
e Wireless Home Security_and Java 


In addition, you may find a great deal of useful information in my older 
publications that are accessible at Programming Oldies But Goodies . 


A low-level mechanism 


Socket programming provides a low-level mechanism by which you can 
connect two computers for the exchange of data. One of those is generally 
considered to be the client while the other is considered to be the server . 


The client initiates a connection with a server. Servers wait for a clients to 
initiate connections. 


A mutually acceptable application protocol 


The governing protocol will determine what happens after the connection is 
made. In order for two computers to communicate effectively, they must 
each implement some mutually acceptable application protocol. 


Data flow 


Socket programming makes it possible for you to cause data to flow in a 
full-duplex mode between a client and a server . This data flow can be 


viewed in almost exactly the same way that we view data flow to and from 
a disk: as a stream of bytes. 


As with most stream data processing, the system is responsible for moving 
the bytes from the source to the destination. It is the responsibility of the 
programmer to assign meaning to those bytes. 


An application protocol 


Assigning meaning takes on a special significance for socket programming. 
In particular, as mentioned above, it is the responsibility of the programmer 
to implement a mutually acceptable communication protocol, at the 
application level, to cause the data to flow in an orderly manner. Some of 
the bytes are used to implement the protocol, and some of the bytes are used 
to transfer data. 


An application protocol is a set of rules by which the programs in the two 
computers can carry on a conversation and transfer data in the process. 


The HTTP protocol 


For example, we will write a very abbreviated form of the HTTP protocol 
to download a web page from a server and to display it as raw text. 


This program will involve adherence to a fairly simple protocol. (At least 
the part that we implement will be simple.) 


The daytime protocol 


We will also write a program that obtains the date and time from the same 
or another computer. In this case, the protocol is about as simple as it can 
possibly be. The client will simply make the connection and listen for a 
string containing the date and time. In this case, the client isn't even 
required to make a request. 


The echo protocol 


We will write another program that sends a line of text to a computer and 
receives an echo of that text. This protocol is only slightly more 


complicated than the daytime protocol in that it is necessary to sent text to 
the other computer in order to elicit a response. 


The application protocol is the hard part 


It is easy to use sockets to write code that will cause a stream of bytes to 
flow in both directions between a client and a server . This is no more 
difficult than causing a stream of bytes to flow in both directions between 
memory and a file on a disk. 


Getting the bytes to flow is the easy part. Beyond that, you must do all of 
the programming to implement an application protocol that is understood 
by both the client and the server . Often that is the more difficult part. 


Discussion and sample code 


Simple TCP/IP services 


This discussion applies to the Windows operating system only. If you are 
using a different operating system you will need to do the necessary 
research to translate this information for use with your operating system. 


See Windows 7 Simple TCP/IP Services - What and How? for more 
detailed information on this topic. 


A simple server 


Windows and some other operating systems make it possible to cause a 
computer to act as a simple server to deliver the following services: 


e Echo on port 7 

e Daytime on port 13 

¢ Quote of the Day on port 17 

e Character generator on port 19 
e Discard on port 9 


This module will be concerned with only the first two. However, to use any 
of them, you must configure your computer to support all of them. 


Configuring your computer 
Do the following to configure your computer to support these services. 


In Windows 7, Vista, and possibly older versions of the Windows operating 
system, do the following: 


e Open the Control Panel 

e Select Programs and Features 

e Select Turn Windows features on or off 

e Scroll down to Simple TCPIP services and check the box 
e Also check the box for Telnet Client 

e Click OK and follow the directions 


On some computers, this may take a long time to complete. (It took more 
than 15 minutes on an older laptop computer that I own.) . 


Test using telnet 


When the process is complete, open a command line window and enter the 
following: 


telnet localhost 13 


You should see something like the contents of Figure 1 if your computer is 
supporting simple TCP/IP services. 


Figure 1 - Successful daytime query. 


Figure 1 - Successful daytime query. 


5:27:30 PM 1/10/2014 


Connection to host lost. 


You can use localhost to do a query on the same machine or you can do a 
query on the name of some other properly configured computer on a local 
area network. 


(You can also use the name of the same computer in place of 
localhost to do a query on the same computer.) 


Opening ports on the firewall 


In the case of accessing another computer on the network, in addition to the 
procedure described above , you may also need to open the required ports in 
the Windows firewall or perhaps a firewall that is being managed by other 
software running on that computer. 


(The ports of interest are shown in the above list .) 


I won't attempt to explain how to open and close ports in the firewall. The 
Windows Help and Support feature explains how to open and close ports in 
the Windows firewall. If the firewall is being managed by another program, 
the documentation for that program should explain how to open and close 
ports. 


Echo program 


This program implements a client that performs a simple echo test by 
sending a line of text to the echo port (port 7) on a server (or on the same 
computer) . 


Overview 


The program begins by instantiating a String object containing the name of 
an echo server that is being used to test the program (localhost as the 
program is shown in Listing_1_) . This is followed by the declaration and 
initialization of an int variable containing the standard echo port number (7) 


Than the program gets a socket connection to port 7 on the server as shown 
in Listing 2 .. 


Following this, the program gets input and output streams from the socket 
and wraps them in the Reader and Writer classes as shown in Listing 3 . 


Once the connection is made and the input and output streams are ready to 
use, the program sends a line of text to the echo port on the specified server 
as shown in Listing 4. This causes the server to send the same line of text 
back to the client. 


The program reads the line of text that is received and displays it in the 
command-line window. 


Finally, the program closes the socket and terminates. 
The program output 


Assuming that you select a computer that supports echo processing on port 
7, the output from this program should be as shown in Figure 2 . 


Figure 2 - Output for a successful echo test. 


echo: This is an echo test 


Beginning of the program named Java4660a 


I will discuss this program in fragments. (I will ignore exception handling 
code.) A complete listing of the program is provided in Listing 12 . The 
beginning of the program is shown in Listing 1 . 


Listing 1 - Beginning of the program named Java4660a. 


import java.net.*; 
import java.io.*; 
import java.util.*; 


Class Java4660a{ 
public static void main(String[] args){ 
String server = "localhost"; 
int port = 7; //echo port 


Listing 1 declares and initializes two local variables to specify the server 
and the port. We will use these variables later. 


Instantiate a Socket object 


Listing 2 shows the key statement in this program insofar as learning new 
material is concerned. 


Listing 2 - Instantiate a Socket object. 


Socket socket = new Socket(server,port); 


The statement in Listing 2 establishes a connection with the specified port 
on the specified server by instantiating a new object of type Socket . 


Once this object exists, it is possible to use it to communicate with the 
server on the specified port using the protocol prescribed for the service 
being delivered on that port. 


The constructor for this class throws two different types of exceptions so 
you will need to wrap this statement in a try/catch block. The two types of 
exceptions are: 


e UnknownHostException 
e IOException 


Get I/O stream objects 


Once you have a Socket object, you can use that object to open input and 
output streams that allow you to transfer data between the client and the 
server using the code shown in Listing 3 . 


Listing 3 - Get I/O stream objects. 


BufferedReader inputStream = 
new BufferedReader (new 
InputStreamReader ( 


socket.getInputStream())); 
Printwriter outputStream = 
new PrintwWriter (new 


OutputStreamwriter ( 


socket.getOutputStream()),true); 


Note that the true parameter in the last line of Listing 3 causes the output 
stream to flush automatically. Proper flushing is an important aspect of 
socket programming. 


Send a line of text to the server and display the echo 


The code in Listing 4 uses the outputStream created above to send a line 
of text to the server, and then uses the inputStream created above to 
capture and display the echo that is returned from the server. 


Listing 4 - Send a line of text to the server and display the echo. 


Listing 4 - Send a line of text to the server and display the echo. 


//Send line of text to the server 

outputStream.println("This 1s an echo 
test"); 

//Get echoed line back from server and 
display it 

System.out.printiln("echo: 
"+inputStream.readLine()); 


//Close the socket 
socket.close(); 


Then Listing 4 closes the socket. 
You can view the remainder of the program in Listing 12. 
The essence of socket programming 


That's really about all there is to socket programming from the client 
viewpoint. 


Beyond this, the programming complexity associated with socket 


programming results from the requirement to implement an application 
protocol that will successfully communicate with the server. 


Date/time program 


This program implements a client that gets the date and time from the 
daytime port (13) on a server that supports that port. 


This program is even simpler than the previous one, because it isn't 
necessary to send anything to the server to get the desired result. All that is 


necessary to cause the server to send the information is to make the 
connection. 


This program gets and displays the date and time on the server at " 
localhost ". However, you can modify the program to access another 
computer in your network if you choose to do so. It is not likely that you 
will find a server on the Internet at large that still supports the daytime port, 
but you can try. 


The program also displays the current date and time in Austin, TX (or 
wherever the program happens to be run) for comparison. 


Beginning of the program named Java4660b 


As usual, I will explain this program in fragments. A complete listing is 
provided in Listing 13 . 


As shown in Listing 5, program begins by instantiating a String object 
containing the name of the server being used to test the program. 


Listing 5 - Beginning of the program named Java4660b. 


Listing 5 - Beginning of the program named Java4660b. 


import java.net.*; 
import java.io.*; 
import java.util.*; 


Class Sockets04{ 
public static void main(String[] args){ 


String server = "localhost"; 
int port = 13; //daytime port 
try{ 


//Get a socket, connected to the 
specified server 

// on the specified port. 

Socket socket = new Socket(server,port); 


This is followed by the declaration and initialization of an int variable 
identifying the standard daytime port: port 13. 


Than the program gets a socket connection to port 13 on the specified 
server. 


Get an input stream 


Following this, the program gets an input stream from the socket and wraps 
it in the reader classes as shown in Listing 6 . 


Listing 6 - Get an input stream. 


Listing 6 - Get an input stream. 


//Get an input stream from the socket 
BufferedReader inputStream = 
new BufferedReader (new 
InputStreamReader ( 


socket.getInputStream())); 


This program doesn't need an output stream because the client doesn't send 
anything to the server. As mentioned earlier, simply connecting is sufficient 
to trigger the server to send the date and time. 


Read and display incoming data 


After the connection is made via the socket and the input stream is ready to 
use, the client reads a line of incoming text as shown in Listing 7. This line 
of text contains the date and time sent by the server. 


Listing 7 - Read and display incoming data. 


Listing 7 - Read and display incoming data. 


System.out.println("Current time at " + 
server); 


System.out.println(inputStream.readLine()); 
System.out.printiln( "Current time in 
Austin, TX:"); 
System.out.println(new Date()); 


//Close the socket 
socket.close(); 


Daytime program output 


The program displays this line of text, and also gets and displays the date 
and time on the local system using the Date class for comparison. 


Figure 3 shows the output for one run of the program. 


Figure 3 - Daytime program output. 


Current time at localhost 
8:29:56 AM 1/12/2014 

Current time in Austin, TX: 
Sun Jan 12 08:29:56 CST 2014 


Then the program closes the socket and terminates. 


Simple browser program 


The next program is an extremely simple web browser program. More 
correctly, the next program is a simple HTTP client implemented using 
sockets. A complete listing of the program is provided in Listing 14 . 


The program implements just enough of the HTTP protocol to make it 
capable of getting a file from an HTTP server. Considerably more 
programming effort would be required to turn it into a useful browser. 


Beginning of the program named Java4660c 


As shown in Listing 8 , the program begins by defining the name of a server 
and the number of the HTTP port on that server. Although the standard port 
number for HTTP servers is port 80, this program is written to access a 
Tomcat server as localhost using port 8080. 


Listing 8 - Beginning of the program named Java4660c. 


Listing 8 - Beginning of the program named Java4660c. 
import java.net.*; 
import java.io.*; 


Class Java4660c{ 
public static void main(String[] args){ 


String server = "localhost"; 
int port = 8080; //http port on localhost 
try{ 


//Get a socket, connected to the 
specified server 

// on the specified port. 

Socket socket = new Socket(server,port); 


Then the program opens a socket to the specified server on the specified 


port. 


Create input and output streams 


As shown in Listing 9 , the program creates input and output stream objects 


for transferring data between the client and the server . 


Listing 9 - Create input and output streams. 


Listing 9 - Create input and output streams. 


//Get an input stream from the socket 
BufferedReader inputStream = 
new BufferedReader (new 
InputStreamReader ( 


socket.getInputStream())); 


//Get an output stream to the socket. 


Note 
// that this stream will autoflush. 
Printwriter outputStream = 
new PrintWriter (new 
OutputStreamwriter ( 


socket.getOutputStream()),true); 


The output stream will autoflush , which is critical. If the output stream isn't 
flushed, the server will not respond properly. (Presumably it may not 
receive all of the data until the stream is flushed.) 


Send a GET command 


The HTTP protocol provides several different commands or requests that 
the client can send to the server. This program implements only the GET 
command. This is a request by the client to find and download a specified 
file. 


Then, as shown in Listing 10, acting as an HTTP client, the program sends 
a GET command to the server specifying a particular path and file name. 
The GET command is part of the HTTP application protocol. 


Listing 10 - Send a GET command. 


outputStream.printin( "GET 
/Java4570b.jsp"); 


Fetch and send 


This causes the server to attempt to fetch the specified file and send it to the 
client. If the server is being properly supported on the specific port, it will 
send something, although that something could be an error message. 


Note that the request includes not only the file name, but also the path to 
that file relative to the directory that the HTTP server software considers to 
be the pseudo-root . This is probably not the actual root directory on the 
server computer, but rather is a logical root. 


The server software is willing to access and deliver files from directories 
relative to this pseudo-root . 


Note that the request is actually made by printing a line of text on the 
stream that is connected to the server. 


Read and display text from the server 


Finally as shown in Listing 11 , the program reads lines of text from the 
input stream and displays them on the standard output device. 


Listing 11 - Read and display text from the server. 


Listing 11 - Read and display text from the server. 


//Declare a String to read lines into. 
String line = null; 


//Loop reading and displaying lines 
until null 
// 1s received. 
while((line = inputStream.readLine()) != 
null) 
System.out.println(line); 


//Close the socket 
socket.close(); 


Output from the simple browser program 


In this particular case, the output was as shown in Figure 4 . 


Figure 4 - Output from the simple browser program. 


Figure 4 - Output from the simple browser program. 


<html> 
<head><title>Java4570b</title></head> 
<body> 


<form method='get' 
action='http://localhost :8080/Java4570b.jsp'> 
<p>Enter a name and press the button</p> 
<p>Name: <input type='text' 
name='firstName'/></p> 
<input type='submit' value='Submit Name'/> 


<br/><br/>Your session ID and list of names 
1is:<br/> 


Empty<br/> 


</form></body></html> 


A curious result 


The requested file was a JSP file consisting of JSP tags embedded in HTML 
code. Curiously, only the HTML code was returned by the server. (I 
suppose it is also possible that the JSP tags were returned but were not 
displayed by the program for some reason.) 


In any event, I will leave it as an exercise for those students who may be 
interested to research the matter. As I mentioned earlier: 


"Getting the bytes to flow is the easy part. Beyond that, you must 
do all of the programming to implement an application protocol 
that is understood by both the client and the server . Often that is 
the more difficult part." 


When there are no more lines to be read, a null is received. This causes the 
client to exit the input loop and to close the socket. 


Run the programs 


I encourage you to copy the code from Listing 12 , Listing 13, and Listing 
14. Compile the code and execute it. Experiment with the code, making 
changes, and observing the results of your changes. Make certain that you 
can explain why your changes behave as they do. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4660: Sockets 
e File: Java4660.htm 

e Published: 03/02/14 

e Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 


should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : | am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


Complete program listings 


Listing 12 - The program named Java4660a. 


/*File Java4660a. java Copyright 1998, R.G.Baldwin 
Revised 01/10/14 


This program performs a simple echo test with 
localhost 

by sending a line of text to the echo port, port 
T. 


The computer must have been previously configured 
to 
support the echo port. 


The output from this program is: 


echo: This is an echo test 


KEKE KEKRKRKEKKEKRKR KEKE KERR KR KEK KEKEKRKE RRR KERR KERR KEKE KKK KKK KEKE KEKEEE 


SR eh 


import java.net.*; 
import java.io.*; 
import java.util.*; 


Class Java4660a{ 
public static void main(String[] args){ 
String server = "localhost"; 
int port = 7; //echo port 


try{ 
//Get a socket, connected to the specified 


server 
// on the specified port. 
Socket socket = new Socket(server, port); 


//Get an input stream from the socket 
BufferedReader inputStream = 
new BufferedReader (new 
InputStreamReader ( 


socket.getInputStream())); 


//Get an output stream to the socket. Note 
// that this stream will autoflush. 
Printwriter outputStream = 
new PrintwWriter (new 
OutputStreamwriter ( 


socket.getOutputStream()),true); 


//Send line of text to the server 

outputStream.println("This 1s an echo 
test"); 

//Get echoed line back from server and 
display it 


System.out.println("echo: 
"+inputStream.readLine()); 


//Close the socket 
socket.close(); 

}//end try 

catch(Exception e){ 
e.printStackTrace(); 

}//end catch 

}//end main 
}//end class Java4660a 


Listing 13 - The program named Java4660b. 


/*File Sockets04. java Copyright 1998, R.G.Baldwin 
Revised 01/10/14 


This program gets and displays the date and time 
on the 
server at "localhost". 


It also displays the current date and time in 
Austin, 
TX, Or wherever the program happens to be run. 


The computer must have been previously configured 
to 
support the daytime port. 


One output from this program was: 


Current time at localhost 
2:39:55 PM 1/10/2014 

Current time in Austin, TX: 
Fri Jan 10 14:39:55 CST 2014 


KKEKEKRKKKKRKRKRKE KEK KEKE KEKE KEKE KK KR KKK KK KE KEKE KEK KEKE KEKE KK KEKE KKK EEE 


SR eh 


import java.net.*; 
import java.io.*; 
import java.util.*; 


Class Sockets04{ 
public static void main(String[] args) { 
String server = "localhost"; 
int port = 13; //daytime port 


try{ 
//Get a socket, connected to the specified 


server 
// on the specified port. 
Socket socket = new Socket(server, port); 


//Get an input stream from the socket 
BufferedReader inputStream = 
new BufferedReader (new 
InputStreamReader ( 


socket.getInputStream())); 


System.out.printin("Current time at " + 
server); 

System.out.println(inputStream.readLine())j; 

System.out.println("Current time in Austin, 
TXi 3 

System.out.println(new Date()); 


//Close the socket 
socket.close(); 

}//end try 

catch(Exception e){ 
e.printStackTrace(); 

}/7end catch UnknownHostException 


}//end main 
}//end class Sockets04 


Listing 14 - The program named Java4660c. 


/*File Java4660c.java Copyright 1998, R.G.Baldwin 
Revised 01/10/14 


This program is a simple http client (web browser) 
implemented using sockets. 


The program implements just enough of the http 
protocol 

to make it capable of getting an html page from an 
http server. 


The program, acting as an http client, sends a GET 
command to the server specifying a particular path 
and 

file name. 


The server is a Tomcat server operating as 
localhost 
on port 8080. 


As of 01/10/14, the output from this program was 
as 
follows. 


<html> 
<head><title>Java4570b</title></head> 
<body> 


<form method='get' 
action='http://localhost :8080/Java4570b.jsp'> 
<p>Enter a name and press the button</p> 
<p>Name: <input type='text' name='firstName'/> 
</p> 
<input type='submit' value='Submit Name'/> 


<br/><br/>Your session ID and list of names is: 
<br/> 


Empty<br/> 


</form></body></html> 


KKEKEKKKKKRKRKE KERR KRKRKR KEKE KK KEKE KEKE KK KEKE KEKE KR KEKE KK KEKE KEKE KEKE EEE 


eRe MS ae ney, 


import java.net.*; 
import java.io.*; 


Class Java4660c{ 
public static void main(String[] args) { 


String server = "localhost"; 
int port = 8080; //http port on localhost 
try{ 


//Get a socket, connected to the specified 
server 

// on the specified port. 

Socket socket = new Socket(server, port); 

//Get an input stream from the socket 

BufferedReader inputStream = 

new BufferedReader (new 

InputStreamReader ( 


socket.getInputStream())); 


//Get an output stream to the socket. Note 
// that this stream will autoflush. 


PrintWriter outputStream = 
new PrintwWriter (new 
OutputStreamwriter ( 


socket.getOutputStream()),true); 


//Send a GET command to the server 
outputStream.printin( "GET /Java4570b.jsp"); 


//Declare a String to read lines into. 
String line = null; 


//Loop reading and displaying lines until 
null 
// is received. 
while((line = inputStream.readLine()) != 
null) 
System.out.printin(line); 


//Close the socket 
socket.close(); 

}//end try 

catch(Exception e){ 
e.printStackTrace(); 

}//end catch 

}//end main 
}//end class Java4660c 


Java4660r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4660: Sockets in the Network Programming sub-collection. 


Table of Contents 


e Preface 
¢ Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4660: Sockets in the Network Programming sub-collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


Sockets in Java come in at least three varieties that are implemented by the 
following Java classes 


e Connector 
e DatagramConnector 
e ServerConnector 


Go to answer 1 


Question 2 
True or False? 


The Socket and DatagramSocket classes represent TCP and UDP 
communications respectively. 


Go to answer 2 


Question 3 
True or False? 


Generally, the ServerSocket class is used to implement both clients and 
servers, while the Socket and DatagramSocket classes are only used to 
implement servers 


Go to answer 3 


Question 4 
True or False? 


Socket programming provides a low-level mechanism by which you can 
connect two computers for the exchange of data. 


Go to answer 4 


Question 5 
True or False? 


Socket programming makes it possible for you to cause data to flow in a 
full-duplex mode between a client and a server . This data flow can be 
viewed in almost exactly the same way that we view data flow to and from 
a disk: as a stream of bytes. 


Go to answer 5 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None fC ex) 
Display your name here. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 5 
True. 


Go back to Question 5 


Answer 4 
True. 


Go back to Question 4 


Answer 3 


False. Generally, the Socket and DatagramSocket classes are used to 
implement both clients and servers, while the ServerSocket class is only 
used to implement servers 


Go back to Question 3 


Answer 2 
True. 


Go back to Question 2 


Answer 1 


False. Sockets in Java come in at least three varieties that are implemented 
by the following Java classes 


e Socket 
¢ DatagramSocket 
e ServerSocket 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4660r-Review 
e File: Java4660r.htm 

e Published: 03/08/14 

e Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4585: Getting Started with Search Engines 
The purpose of this module is to get you started with Search Engines 


Table of Contents 


e Preface 

e Servlets, search engines, or JSON 
e Search engines 

e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
The purpose of this module is to get you started with Search Engines. 


Servlets, search engines, or JSON 


As explained in the page titled Java4510: Preface to INEW 2338 , only one 
of the topics Search Engines , Servlets , or JSON is covered in the course in 
any particular semester. However, all three are important. The course 
material in the Blackboard course management program indicates which 
topic is covered in the current semester. 


Students are encouraged to study all three topics for their own educational 
purposes in order to enhance their prospects of landing a job as a Java 
programmer. 


Search engines 


An understanding of search engines is a valuable skill for a programming 
student to acquire. Furthermore, it is practical for an instructor to assess a 
student's understanding of and ability to develop a web search engine 
written in Java. This assessment can be based solely on practical 
programming assignments along with a written test. 


The search-engine assignments can be written and tested on any computer 
capable of running the Java Standard Edition development kit (including 
the computers in the on-campus labs) with no requirement to install any 
special software. 


The ability to develop a rudimentary search engine doesn't require any 
knowledge of Java programming beyond that which the student should 
already have acquired in this and the prerequisite courses. However, it does 
require the student to do independent research into the syntax and structure 
of HTML web pages and to combine that knowledge with prior knowledge 
of Java programming. Thus, this search-engine competency requirement 
tests the student's ability to apply prior Java programming knowledge to a 
very useful real-world scenario -- search engines. 


Students will be provided the source code for a rudimentary Java web 
crawler that can be used as a starting point for the development of the 
search engine required for each assignment. Students who have completed 
the prerequisite courses should have no difficulty understanding the code in 
that program. It will be the responsibility of the student to modify and 
upgrade the web crawler program in such a way as to satisfy the 
specifications for each programming assignment. 


Students will also be provided links to several online search-engine 
resources along with review questions and answers for use in preparing for 
the written test. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


¢ Module name: Java4585: Getting Started with Search Engines 
e File: Java4585.htm 

Published: 05/17/15 

Revised: 06/02/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4590r-Review for search engines 

This module contains review questions and answers on search engines 
along with hyperlinks to online material from which those questions and 
answers were derived. 


Table of contents 


e Preface 
e Questions 
° 1, 25.0585 D; 05 23 Os 2, 10, 11, 12, 13, 14,15 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching 
INEW2338 Advanced Java Programming at Austin Community College in 
Austin, TX. 


This module contains review questions and answers on search engines 
along with hyperlinks to online material from which those questions and 
answers were derived. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? The robots lockout standard , also known as the robots 
lockout protocol or robots.txt protocol , is a standard used by websites to 
communicate with web crawlers and other web robots. 


Go to answer 1 


Question 2 


True or False? The robots exclusion standard specifies the instruction 
format to be used to inform the robot about which areas of the website 
should not be processed or scanned. 


Go to answer 2 


Question 3 


True or False? All robots cooperate with the robots exclusion standard 
including email harvesters, spambots and malware robots that scan for 
security vulnerabilities. 


Go to answer 3 


Question 4 


True or False? When a site owner wishes to give instructions to web robots 
they place a text file called robots.txt in the root of the web site hierarchy 
(e.g. https://www.example.com/robots.txt). This text file contains the 
instructions in a specific format. Robots that choose to follow the 
instructions try to fetch this file and read the instructions before fetching 
any other file from the web site. If this file doesn't exist, web robots assume 
that the web owner wishes to provide no specific instructions, and crawl the 
entire site. 


Go to answer 4 


Question 5 


True or False? Marking an area of a site "out of bounds" with robots.txt 
guarantees exclusion of all web robots. 


Go to answer 5 


Question 6 


True or False? To cause a webpage to perform better in search engine 
listings, the most important content should be in Flash files. 


Go to answer 6 


Question 7 
True or False? Search engines have two major functions: 


1. crawling and building an index, and 
2. providing search users with a ranked list of the websites they've 
determined are the most relevant. 


Go to answer 7 


Question 8 


True or False? The link structure of the web serves to bind all of the pages 
together. Links allow the search engines' automated robots, called 
"crawlers" or "spiders," to reach the many billions of interconnected 
documents on the web. Once the engines find these pages, they decipher the 
code from them and store selected pieces in massive databases, to be 
recalled later when needed for a search query. 


Go to answer 8 


Question 9 
True or False? Search Engine Optimization (SEO) is the process of 
affecting the visibility of a website or a web page in a search engine's 


unpaid results - often referred to as "natural," "organic," or "earned" results. 


Go to answer 9 


Question 10 


True or False? When a person performs an online search, the search engine 
begins crawling the web and returning a list of all connected hyperlinks that 
are encountered. 


Go to answer 10 


Question 11 


True or False? Search engines typically assume that the more popular a site, 
page, or document, the more valuable the information it contains must be 


Go to answer 11 


Question 12 


True or False? The prototype for the Google search engine was developed 
at MIT. 


Go to answer 12 


Question 13 


True or False? One of the main contributions to improved search engine 
performance, developed by Brin and Page, was PageRank . 


Go to answer 13 


Question 14 


True or False? PageRank is an algorithm used by Google Search to rank 
websites in their search engine results. PageRank was named after Larry 
Page, one of the founders of Google. PageRank is a way of measuring the 
importance of website pages. According to Google: PageRank works by 
counting the number and quality of links to a page to determine a rough 
estimate of how important the website is. The underlying assumption is that 
more important websites are likely to receive more links from other 
websites 


Go to answer 14 


Question 15 


True or False? PageRank is the only algorithm used by Google to order 
search engine results. 


Go to answer 15 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None Cox) 


Display your namethiete. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 15 


False. PageRank is not the only algorithm used by Google to order search 
engine results, but it is the first algorithm that was used by the company, 


and it is the best-known. (See http://en.wikipedia.org/wiki/PageRank .) 


Go back to Question 15 


Answer 14 


True. (See http://en.wikipedia.org/wiki/PageRank .) 


Go back to Question 14 


Answer 13 


True. (See http://en.wikipedia.org/wiki/Search engine optimization .) 


Go back to Question 13 


Answer 12 


False. The prototype for the Google search engine was developed by Sergy 
Brin and Lawrence Page at Stanford. (See The Anatomy of a Large-Scale 
Hypertextual Web Search Engine .) Apparently that prototype search engine 
was known as "Backrub". 


Go back to Question 12 


Answer 11 


operate .) 


Go back to Question 11 


Answer 10 


False. When a person performs an online search, the search engine scours 
its corpus of billions of documents, (which was created earlier by crawling 
and indexing web sites) and does two things: first, it returns only those 
results that are relevant or useful to the searcher's query; second, it ranks 
those results according to the popularity of the websites serving the 
information. It is both relevance and popularity that the process of Search 
Engine Optimization is meant to influence. (See http://moz.com/beginners- 
guide-to-seo/how-search-engines-operate .) 


Go back to Question 10 


Answer 9 


True. (See http://en.wikipedia.org/wiki/Search_ engine optimization .) 


Go back to Question 9 


Answer 8 


operate .) 


Go back to Question 8 


Answer 7 


operate .) 


Go back to Question 7 


Answer 6 


False. To cause a webpage to perform better in search engine listings, the 
most important content should be in HTML text format. Images, Flash files, 
Java applets, and other non-text content are often ignored or devalued by 
search engine crawlers. The easiest way to ensure that the words and 
phrases you display to your visitors are visible to search engines is to place 
them in the HTML text on the page. (See http://moz.com/beginners-guide- 
to-seo/basics-of-search-engine-friendly-design-and-development .) 


Go back to Question 6 


Answer 5 


False. Despite the use of the terms "allow" and "disallow", the robots 
exclusion standard is purely advisory. It relies on the cooperation of the 
web robot, so that marking an area of a site "out of bounds" with robots.txt 
does not guarantee exclusion of all web robots. (See 
http://en.wikipedia.org/wiki/Robots_ exclusion standard .) 


Go back to Question 5 


Answer 4 


True. (See http://en.wikipedia.org/wiki/Robots_ exclusion standard .) 


Go back to Question 4 


Answer 3 


False. Not all robots cooperate with the standard including email harvesters, 
spambots and malware robots that scan for security vulnerabilities. (See 
http://en.wikipedia.org/wiki/Robots exclusion standard .) 


Go back to Question 3 


Answer 2 


True. (See http://en.wikipedia.org/wiki/Robots_ exclusion standard .) 


Go back to Question 2 


Answer 1 


False. The robots exclusion standard , also known as the robots exclusion 
protocol or robots.txt protocol , is a standard used by websites to 
communicate with web crawlers and other web robots. (See 


http://en.wikipedia.org/wiki/Robots_ exclusion standard ) 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


¢ Module name: Java4590r-Review for search engines 
e File: Java4590r.htm 
e Published: 05/04/15 


Note: Disclaimers: 
Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 


possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4530: Getting Started with Servlets 
The purpose of this module is to get you started writing, deploying, and 
testing Java servlets. 


Table of Contents 
e Preface 


o Servlets, search engines, or JSON 
°o Getting started 
o Viewing tip 


=» Figures 
= Listings 


e General background information 


o Test for a successful connection on localhost 
o Upgrading your Java development environment 


e Discussion and sample code 
e What's next? 

e Miscellaneous 

¢ Complete program listings 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
The purpose of this module is to get you started writing, deploying, and 
testing Java servlets. 


Servlets, search engines, or JSON 


As explained in the page titled Java4510: Preface to INEW 2338, only one of 
the topics Search Engines , Servlets , or JSON is covered in the course in any 
particular semester. However, all three are important. The course material in 


the Blackboard course management program indicates which topic is covered 
in the current semester. 


Students are encouraged to study all three topics for their own educational 
purposes in order to enhance their prospects of landing a job as a Java 
programmer. 


Getting started 


If you haven't done so already, I strongly recommend that you study the 
following two modules before continuing with this module: 


e Java4307: Servlets and JSP 
e Java4308: Deploying JSP and Servlets 


While studying Java4308 , I recommend that you download, install on your 
local machine, and test the Apache Tomcat web server. Eventually students 
enrolled in this course will deploy and test their servlet programs on a web 
server operated by the college. However, the first several modules in this sub- 
collection will expect students to deploy and test servlets on a local web 
server. 


Viewing tip 


I recommend that you open another copy of this module in a separate browser 
window and use the following links to easily find and view the Figures and 
Listings while you are reading about them. 


Figures 


e Figure 1. Web server test. 

e Figure 2. Inew2338_050.java. 
e Figure 3. Inew2338_051.java. 
e Figure 4. Inew2338_052.jsp. 


Listings 


e Listing 1. Inew2338_050.java. 
e Listing 2. Inew2338_051.java. 
e Listing 3. Inew2338_052.jsp. 


General background information 


Test for a successful connection on localhost 


Assuming that you have properly installed the Tomcat web server on your 
machine, you should be able to start the server and point your browser to 
http://localhost:8080/ to see something similar to Figure 1 in your browser. 


Figure 1 - Web server test. 


) Apache Tomcat/8.0.0-RC5 - Mozilla Firefox 


[ae Bookmarks oan 


Home Documentation Configuration Examples Wiki 


Apache Tomcat/8.0.0-RC5 eS?" 


If you're seeing this, you've successfully 
Congratulations! 


T™ 


Recommended Reading: 


HOW-TO 
Clustering/Session Replication HOW-T 
Developer Quick Start 
Tomcat Setup Realms & AAA Examples 


First Web Application JDBC Data Sources 


Managing Tomcat Documentation 
For security, access to the Tomcat 8.0 Documentation 
Tomcat 8.0 C on 
SCATALINA_HOME/conf/tomcat-users. Tomcat Wiki 
In Tomcat 8.0 access to the Find additional important 
_ Manager application is split 


configuration information in: swf 
> 


If you don't see that, you should probably rectify the problem before 
continuing. 


While you are there, stop and examine the page showing in your browser 
window. It is packed with information regarding Tomcat, including 
documentation and the source code for numerous servlet and JSP examples. 


Upgrading your Java development environment 


In Java4308 , I showed you how to upgrade your Java development 
environment to include two jar files named 


e servlet.jar 
e server.jar 


I also explained that only the first one may actually be required, but since they 
are both small, there is no harm in having both of them on your machine. 


I showed you how to create a batch file for compiling your servlet. The batch 
file that I provided includes these jar files on the classpath. This has the effect 
of making the following packages, among others, available to your compiler. 
This is a requirement for writing and compiling servlets and JSP. 


e javax.servlet 
e javax.servlet.http 
e javax.servlet.jsp 


You should make certain that you can successfully compile, deploy, and 
access the sample servlet that I provided in Java4308 before continuing with 
this module. 


Discussion and sample code 


Before leaving this module, lets make absolutely certain that everything is 
working by creating, compiling, deploying, and accessing two servlets and 
one JSP. 


Using what you learned in Java4308 , create compile and deploy the two 
servlets shown in Listing 1 and Listing 2. Then create and deploy the JSP 
shown in Listing 3 . 


Start your server and point your browser to 
http://localhost:8080/Inew2338_050 in order to see Figure 2 in your 
browser. 


Figure 2 - Inew2338_050.java. 


} Inew2338_050 - Mozilla Firefox 


“File Edit View History Bookmarks Tools Help 


B-com F) et 


Hello Big Red World 


Point your browser to http://localhost:8080/Inew2338_051 in order to see 
Figure 3 in your browser. 


Figure 3 - Inew2338_051.java. 


) Inew2338_051 - Mozilla Firefox 


a ae 


= 


{ a @ localhost:3030/Inew2333_051 


Hello Big Green World 


Point your browser to http://localhost:8080/Inew2338_052.jsp in order to 
see Figure 4 in your browser. 


Figure 4 - Inew2338_052.jsp. 


) My title - Mozilla Firefox 


File Edit View History Bookmarks Tods Help 
ral | my title [“]ine 


€ ) @ localhost:3030/Inew2338_052.jsp @ || BY ~ coole 
es 


P| & ft 


@ Share Browser WebEx | 
My JSP Page 


Hello, JSP world! 


WU & Whe © 


Isn't this fun 


What's next? 


If those tests were successful, your system is ready for you to move on to the 


next module and begin learning the programming details required to create 
Java servlets. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4530: Getting Started with Servlets 
e File: Java4530.htm 
e Published: 12/19/13 


e Revised: 06/02/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it possible 
for you to purchase a pre-printed version of the PDF file, you should be 
aware that some of the HTML elements in this module may not translate well 
into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 

In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales nor 
do I know who does receive compensation. If you purchase such a book, 
please be aware that it is a copy of a module that is freely available on 
cnx.org and that it was made and published without my prior knowledge. 
Affiliation : | am a professor of Computer Information Technology at Austin 
Community College in Austin, TX. 


Complete program listings 


Listing 1 - Inew2338_050.java. 


/*File Inew2338_050. java, 
Copyright 2004, R.G.Baldwin 


The servlet produces the following text in the 


Listing 1 - Inew2338_050.java. 
browser window in large red letters. 


Hello Big Red World 

RR ae SOR ee Dee SOS Ie Be Pe ae ee ee Ie Oe PS ae ee ee RF 
import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 


public class Inew2338_050 extends HttpServlet{ 
public void doGet(HttpServletRequest req, 
HttpServletResponse res) 
throws ServletException, 
IOException{ 


res.setContentType("text/html"); 
PrintWriter out = res.getWriter(); 


out.printin("<HTML>") ; 

out.printin( 
"<HEAD><TITLE>Inew2338_050</TITLE></HEAD>" ) ; 

out.printin("<BODY>") ; 


out.printin("<h1 align=\"center\">" 

+"<font color=\"#FFOOOO\">"); 
out.printin("Hello Big Red World"); 
out.printin("</font></h1>"); 


out.printin("</BODY></HTML>" ) ; 
}//end doGet() 
}//end class Inew2338_050 


Listing 2 - Inew2338_051.java. 


Listing 2 - Inew2338_051.java. 


/*File Inew2338_051.java 
Copyright 2004, R.G.Baldwin 


The servlet produces the following text in the 
browser window in large green letters. 


Hello Big Green World 

FRIED REM SETI MFRS ROPE Be gn Ne RRO Be a NA, Ae EO, ee, A, RN Re ER Tee 
import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 


public class Inew2338_051 extends HttpServlet{ 
public void doGet(HttpServletRequest req, 
HttpServletResponse res) 
throws ServletException, 
IOException{ 


res.setContentType("text/html"); 
PrintWriter out = res.getWriter(); 


out.printin("<HTML>") ; 

out.println( 
"<HEAD><TITLE>Inew2338_051</TITLE></HEAD>" ) ; 

out.printiln("<BODY>") ; 


out.printin("<h1 align=\"center\">" 

+"<font color=\"#00FFOO\">"); 
out.printin("Hello Big Green World"); 
out.printin("</font></h1>"); 


out.printin("</BODY></HTML>" ) ; 
}//end doGet() 
}//end class Inew2338_051 


Listing 2 - Inew2338_051.java. 


Listing 3 - Inew2338_052.jsp. 


<!--File Inew2338_052.jsp --> 


<html> 
<title>My title</title> 
<body> 
<H1>My JSP Page</H1> 
<H2>Hello, JSP world!</H2> 


<% for (int 1=0; 1<6; i++) { %> 
<br> 
<%= 1 %> 

<% }//end for loop %> 

<H3>Isn't this fun</H3> 


</body> 
</html> 


-end- 


Java4530r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4530: Getting Started with Servlets in the Servlets sub-collection. 


Table of Contents 


e Preface 
¢ Questions 
0 12 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4530: Getting Started with Servlets in the Servlets sub-collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


Assuming that you have properly installed the Tomcat web server on your 
local machine, you should be able to start the server and point your browser 
to http://localhost:80/ to see the Tomcat startup screen in your browser. 


Go to answer 1 


Question 2 
True or False? 


Including the following packages on your classpath is a requirement for 
writing and compiling servlets and JSP. 


e javax.servlet 
e javax.servlet.http 
e javax.servlet.jsp 


Go to answer 2 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None eles 


Display your nametiere. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 2 


True. 


Go back to Question 2 


Answer 1 


False. Assuming that you have properly installed the Tomcat web server on 
your local machine, you should be able to start the server and point your 
browser to http://localhost:8080/ to see the Tomcat startup screen in your 
browser. (Note the port number.) 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4530r-Review 
e File: Java4530r.htm 

e Published: 03/10/14 

e Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 


In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4535: Introduction to Servlet Code 
This module introduces you to the coding of Java servlets. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


o The program named Servlet0O1.java 
o Interesting code fragments 
o But wait, there's more 


e What's next? 
e Miscellaneous 
¢ Complete program listing 


Preface 


This module is one in a collection of modules designed for teaching INEW 2338 Advanced 
Java (Web) at Austin Community College in Austin, TX. 


Viewing tip 


I recommend that you open another copy of this module in a separate browser window and 
use the following links to easily find and view the Figures and Listings while you are reading 
about them. 


Figures 


e Figure 1. Output from Servlet01.java. 


Listings 


¢ Listing 1. Import directives. 


e Listing 2. Beginning of the class definition. 

¢ Listing 3. Beginning of the overridden doGet method. 
e Listing 4. Preparing to return a response. 

e Listing 5. Construct and return an HTML file. 

e Listing 6. Servlet01.java. 


General background information 


Servlets are modules that run inside request/response-oriented servers, such as Java-enabled 
web servers, and extend them in some manner. For example, a servlet might be responsible 
for taking data in an HTML order-entry form and applying the business logic used to update 
a company's order database. 


Servlets are to servers what applets are to browsers. The Servlet API, which you use to write 

servlets, assumes nothing about how a servlet is loaded, the server environment in which the 

servlet runs, or the protocol used to transmit data to and from the user. This allows servlets to 
be embedded in many different web servers. 


Servlets are an effective substitute for CGI scripts. They provide a way to generate dynamic 
documents that is both easier to write and faster to run. They also address the problem of 
doing server-side programming with platform-specific APIs. 


In some ways, a servlet is similar to an applet. An applet is a chunk of Java code that 
executes under control of a browser. A servlet is a chunk of Java code that executes under 
control of a server program. 


You must run your servlet under the control of a Java-enabled server program. The first few 
modules in this sub-collection will use the Apache Tomcat server for that purpose. 


Please note that the use of servlets is not restricted to HTTP servers. However, the discussion 
in this lesson and most of the follow-on modules will generally apply only to HTTP servers. 


Discussion and sample code 


The program named Servlet01.java 


In this module, I will discuss servlets using a sample servlet program named Servlet01.java 
as a guide. A complete listing of the program is shown in Listing 6. 


This program will illustrate some, but not all of material that I will discuss in this module. 
The purpose of this program is to illustrate a very simple servlet and to serve as a vehicle for 
discussion of various aspects of servlets. 


The servlet produces the screen output in the browser shown in Figure 1. 


Figure 1 - Output from Servlet01.java. 


) Serviet01 - Mozilla Firefox lol x) 


X Java4308: Deploying JSP and Servlets I Gil servetot x| + | 
€& » @ localhost:3080/Servieto1 C || BB Google p| + f 


@ Share Browser WebEx~ | 


Hello Big Red World 


Interesting code fragments 


Import directives 


I will explain the program code in fragments. The first fragment in Listing 1 shows the 
import directives necessary to support servlet programming. 


Listing 1 - Import directives. 


import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.* 


The Servlet interface 


All servlets must implement the Servlet interface. You can implement it directly. However, it 
is more common to implement it indirectly by extending a class that implements the interface 
(such as HttpServlet ). 


The Servlet interface declares methods for managing the servlet and its communications 
with clients. You will need to override some or all of those methods when you write your 
servlet. 


Listing 2 shows the beginning of the controlling class for the servlet. Note that the servlet 
class extends HttpServlet . By extending the HttpServlet class, the servlet implements the 
Servlet interface indirectly. 


Listing 2 - Beginning of the class definition. 


public class Servlet01 extends HttpServlet{ 


Request and response objects 
Two object references are passed to a servlet when it called by a client: 


¢ ServietRequest - encapsulates the communication from the client to the server. 
¢ ServietResponse - encapsulates the communication from the servlet back to the client 


Access to these objects can be accomplished in more than one way. This servlet overrides the 
doGet method, which receives references to the two objects as incoming parameters. 


The overridden doGet method 


The beginning of the overridden doGet method is shown in Listing 3 . 


Listing 3 - Beginning of the overridden doGet method. 


public void doGet(HttpServletRequest req, 
HttpServletResponse res) 
throws ServletException, 
IOException{ 


Note that the doGet method throws an exception of type ServletException . In this servlet, 
some of the code inside the doGet method also throws an IOException , which is not 
handled inside the method. Thus, it is declared in the method signature. 


Browser commands and servlet methods 


A Java-enabled server provide a method corresponding to each of the commands that an 
HTTP client can send to its server. When the server receives a command from the client, the 
corresponding method is called on the servlet. 


As the servlet programmer, you override some or all of those methods to provide the desired 
behavior. 


The doGet method and the HTTP GET command 


The doGet method corresponds to the HTTP GET command. If you don't override the 
method, the default implementation reports an HTTP BAD_REQUEST error when the 
browser sends a GET command. 


Overriding the doGet method to support the GET command also automatically supports the 
HTTP HEAD command. 


(The HEAD command is a GET command that returns no body in the response. It just 
returns the requested header fields.) 


The fundamental purpose of the GET command makes it possible for the client to get 
something from the server. When you override the doGet method, you should 


e Read data from the request 

¢ Construct the proper headers in the response 

e Gain access to either the writer or the output stream (depending on whether the material 
to be returned is text or binary data) 

e Write the response data 


Responding to the request 


The headers should include content type and encoding. The content type must be set before 
the writer is accessed. 


This servlet constructs and returns a simple HTML file containing formatted text. Listing 4 
shows the use of setContentType method of the response object to set the content type being 
returned before accessing the writer. Then the getWriter method of the response object is 
used to get access to the output stream. 


Listing 4 - Preparing to return a response. 


Listing 4 - Preparing to return a response. 


res.setContentType("text/html"); 
Printwriter out = res.getWriter() 


You will need to do some research on your own to learn about the different content types that 
can be returned by a servlet. 


The PrintWriter object referred to by out is used to construct output text in Listing 5 . 
Construct and return an HTML file 


That brings us to the fragment in Listing 5, which constructs and returns the various 
elements of an HTML page and then terminates the doGet method. 


Listing 5 - Construct and return an HTML file. 


out.println("<html>"); 
out.printin("<head><title>Servlet01</title></head>"); 
out.printin("<body>"); 


out.printin("<h1i align=\"center\">" 
+"<font color=\"#FFOOOO\">") ; 

out.printin( "Hello Big Red World"); 

out. printin("</font></h1>") ; 


out.println("</body></htm1>") ; 


}//end doGet() 
}//end class Servlet01 


Constructing the HTML code 


The code in Listing 5 constructs a series of String objects and passes them as parameters to 
the println method of the PrintWriter object referred to by out . The content of the String 


objects is raw HTML code. 


Note: A tedious process: 

Constructing raw HTML code as a series of Java String objects can be a very tedious and 
elror-prone process, due particularly to the frequent need to use the backslash escape 
character for quotation marks inside the strings. (All attribute values in HTML must be 
surrounded by quotation marks.) 

This is one of the arguments for the use of JSP that you learned about in the prerequisite 
course .. One of the benefits of JSP is that it can greatly reduce the amount of raw HTML 
code that you must construct to send back a typical HTML web page. 


If you have written any raw HTML code, you will probably recognize the construction of the 
HTML code in Listing 5 (and you may also recognize the HTML code as being vintage 1999 
when the servlet program was written) . 


If you haven't written any HTML, you will need to do a little research on your own to learn 
about the various parts of an HTML page. At this level, it is fairly simple. 


(An HTML element often consists of text content surrounded by opening and 
closing tags of a particular type. Elements can also be nested inside of other 
elements creating a hierarchical tree of elements.) 


The content between the opening and closing body tags in Listing 5 represents the real 
information content of the page. The rest is mostly formatting information. 


This body content in Listing 5 says to 


e Set the text to style h1 (which is a maximum size header). 

e Center it on the page. 

e Set the color to hexadecimal FFO000, which is the color value for pure red (in a red, 
green, blue color system) . 


Most (but not all) HTML elements, such as the body element, require an opening tag and a 
closing tag. Thus, most tag types come in pairs. 


An HTML page is pure text with the various elements specifying how the browser is to 
interpret and display that text. (The text can also refer to other files such as image files and 
cause the content of those files to be included in the rendered output produced by the 
browser.) 


The Java code in this servlet simply prints the requisite HTML text to the output stream 
referred to by out . Recall from Listing 4 that the reference to the output stream was obtained 
by calling the getWriter method on the HttpServerResponse object. That object takes care 
of transporting the text back to the client browser. 


But wait, there's more 


Usually in most modules, when I complete the discussion of the last sample program, that is 
the end of the module. In this module, however, there are several other important topics that I 
want to discuss before ending the module. 


The ServletRequest object 


One of the incoming objects to the servlet is of type ServletRequest . This is not the name of 
a class. Instead, this is a type defined by an interface of the same name. This interface 
declares more than 30 methods by which the servlet can extract incoming information from 
the object. This framework provides the servlet's only access to incoming data. 


The data provided by the ServletRequest o object includes parameter names and values, 
attributes, and an input stream. 


Interfaces that extend ServletRequest can provide additional protocol-specific data. For 
example, HTTP data is provided by the interface HttpServletRequest , which extends 
ServletRequest . (Recall from Listing_3 t that the doGet method receives a reference to an 
HttpServletRequest object as an incoming parameter.) 


Suffice it to say that it is possible for the servlet to obtain a great deal of information in order 
to carry out its duties. (I will refer you to the online documentation for more information 
about the available methods.) 


The ServletResponse object 

The other incoming object to the servlet is an object of type ServletResponse . This is also a 
type defined by an interface of the same name. This interface declares more than 15 methods 
by which the servlet can return data to the client. 


The content type 


Recall that Listing 4 calls the setContentType m method on the response object to set the 
type of the data being returned by this servlet to "text/html". It is also possible to set the 
character encoding in a call to setContentType with something like 


text/html;charset=UTF-8 


The rules for doing that are fairly complicated, so you would do well to consult the Java 
documentation for the setContentType method before trying to deal with that possibility. 


Persistence 


We have discussed the classes and interfaces that make up a basic Servlet. HTTP servlets 
have additional objects that provide session-tracking capabilities. The servlet writer can use 
these APIs to maintain state between the servlet and the client that persists across multiple 
connections during some time period. 


The servlet life cycle 


Servlets have a prescribed life cycle. Servers load and run servlets. Servers accept requests 
from clients, and may use their servlets to return data to the clients. 


Servers can also remove servlets. So, the stages of a servlet's life cycle are: 


e The servlet is loaded and initialized. 
e The servlet is used to satisfy client requests. 
e The servlet is removed or unloaded. 


A server runs the servlet's init method when it loads the servlet. Most servlets are run in 
multi-threaded servers. However, there are no concurrency issues during servlet 
initialization. The server calls the init method when it loads the servlet, and does not call it 
again unless it is reloading the servlet. 


The server cannot reload a servlet until after it has removed the servlet by calling the destroy 
method. Initialization is allowed to complete before client requests are handled or the servlet 
is destroyed. 


A practical problem 


This can be a problem when you are developing a servlet and repeatedly testing it with a 
server. Once the servlet is initially loaded from the class file, for some servers simply 
providing a new class file does not cause the server to remove the old version of the servlet 
and load the new version. (This appears to be the case with the Apache Tomcat server that 
we will be using for some of these modules.) 


With the Apache Tomcat server , you must stop and restart the server to cause it to load the 
new version of a servlet. (It may be possible to use some feature of the administration tool to 
force the server to remove an old version and load a new version of a servlet without 
stopping and restarting the server but I have never investigated that possibility.) 


The second stage 


The second stage in the life of the servlet begins after the servlet has been loaded and 
initialized. At that point, the server may call upon the servlet to respond to client requests. In 


so doing, the servlet handles client requests by processing them in its service method, which 
is called by the server. Normally, the service request from each client is run in a separate 
thread by the servlet. 


Generic versus HTTP servlets 


If you are writing a generic servlet, you will probably override the service method. However, 
if you are writing servlets to be used with HTTP servers, you probably won't need to override 
service . The service method of the HttpServlet class handles the setup and dispatches the 
request to methods such as doGet and doPost . When writing HTTP servlets, you will 
normally extend the HttpServlet class and override the doX XX methods instead of 
overriding the service method. 


Multithreaded operation 


Servlets can process requests from multiple clients concurrently in a multithreaded manner. 
This means that the service methods should be written to be thread safe. One description that 
I have seen for how to write a thread-safe method is to: 


Use the fewest possible number of instance variables, and synchronize access to 
them if you use them. 


Single-threaded operation 


In some cases and for some reason known only to you, you may decide to prevent your 
servlet from processing concurrent client requests. In this case, you should cause your servlet 
to implement the SingleThreadModel interface. This interface guarantees that no two 
threads will execute the servlet's service methods concurrently. Implementing the interface 
does not require writing any extra methods. Merely declaring that the servlet implements the 
interface is sufficient to prevent the server from making concurrent calls to the service 
method. 


(This may not make you popular with the server administrator because it could 
cause your single-threaded servlet to become a bottleneck.) 


The third stage 


The third and last stage of a servlet's life cycle is removal. When a server removes a servlet, 
it runs the servlet's destroy method. This method is run only once. The server will not run it 
again until after it reloads and reinitializes the servlet. When the destroy method runs, other 


threads might be running service requests. If it is necessary to access shared resources while 
doing cleanup, that access should be synchronized. 


The javax.servlet.Servlet interface 


Servlets must implement the javax.servlet.Servlet interface. For writing servlets that run 
under control of servers that use the HTTP protocol, the most common way to write servlets 
is to extend the javax.servlet.http.HttpServlet class which is a way to indirectly implement 
the Servlet interface. 


The HttpServlet class implements the Servlet interface by extending the 
GenericServlet base class, and provides a framework for handling the HTTP 
protocol. 


Four methods 


For servlets that extend the HttpServlet class, the following four methods may be 
overridden to cause your servlet to interact with the client. 


¢ doGet - for handling GET, conditional GET and HEAD requests 
e doPost - for handling POST requests 

¢ doPut - for handling PUT requests 

¢ doDelete - for handling DELETE requests 


You may need to do some outside research on the HTTP protocol to learn about the nature of 
each type of client request listed above. You may also want to go back and review Java4350: 
Form Processing with JSP for information regarding the differences between the HTML 
GET and POST methods. 


By default, if called but not overridden, these methods return a BAD_REQUEST (400) error. 
The servlet discussed earlier used the doGet method to handle GET requests. 

Differences between doGet and doPost 

I will describe a couple of differences between the two methods that you may find useful. 
Assume there is a servlet named Java4550a on a localhost web server. You can execute that 
servlet by typing the following address into the address field of the browser and pressing the 
Enter key : 

http://localhost:8080/Java4550a 


First consider the contents of the browser's address window. When an HTML page calls the 
doGet method of a servlet named Java4550a , you will often see something like the 


following in the address window: 
http://localhost:8080/Java4550a?firstName=Dick... 


As you can see, some information has been appended onto the end of the address with the ? 
character being used to separate the two. 


However, if the HTML page calls the doPost method of the same servlet, this is what you 
should see: 


http://localhost:8080/Java4550a 


(Note that some browsers don't display the http:// portion of the address.) 


In other words, with the doPost method, no visible information is appended onto the actual 
address as is the case with the doGet method. 


It is probably also safe to say that the doGet method is the default. By this, I mean that if you 
enter address given above into the browser's address field and press the Enter key, the doGet 
method (and not the doPost method) belonging to the servlet named Java4550a will be 
called. 


(The same is true if you put this address into a simple hyperlink when creating a 
web page.) 


If you want to manually enter an address into the address field and cause the doPost method 
to be called, you must find some other way to do it. 


Arguments 


Each of the methods requires two arguments. The first, a reference to an 
HttpServletRequest object, encapsulates the data from the client. The second, a reference to 
an HttpServletResponse object encapsulates the response to the client. 


The HttpServletRequest object provides a large number of methods that the servlet can use 
to obtain information about the request. 


Similarly, the HttpServletResponse object provides a large number of methods that the 
servlet can use to return data to the client. 


The init and destroy methods 


You may also find that you need to override the init and destroy methods in your servlet. 
Recall that each of these methods is called only once. The init method is called when the 
server loads the servlet class. The destroy method is called when the server removes the 
servlet class. 


Overriding the init method 


The servlet should use the init method to prepare the resources it manages and to make the 
servlet ready to handle client requests. It can do this without regard for multi-threading issues 
because it is guaranteed that there is only a single thread running during initialization. If the 
init method is unable to run to a successful completion, it should throw an 
UnavailableException object. 


The init method receives a ServletConfig object as a parameter. For reasons that I won't 
bother to discuss here, the overridden init method should call super.init and pass this 
configuration object as a parameter. If you are curious as to the reasons, you can look it up in 
the documentation. 


Overriding the destroy method 


Overriding the destroy method is more problematic, particularly if it is necessary to deal with 
resources that may be shared by service threads that are still running when the server decides 
to remove the servlet and call its destroy method. I'm going to punt on this one, and suggest 
that if you find yourself in this situation, you should find a good book with an example 
similar to your situation and use that example for guidance. 


The getServletInfo method 

Some applications may want to display information about a servlet, such as a short 
description of the purpose of the servlet, its author, and perhaps its version number. The 
Servlet API provides a method named getServletInfo to return this kind of information 


about the servlet. By default, this method returns null. You can override this method to return 
a String containing information about your servlet. 


What's next? 


The next module in the series will take on forms and databases. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


¢ Module name: Java4535: Introduction to Servlet Code 
File: Java4535.htm 

Published: 12/20/13 

e Revised: 01/31/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to download a PDF file 
for this module at no charge, and also makes it possible for you to purchase a pre-printed 
version of the PDF file, you should be aware that some of the HTML elements in this 
module may not translate well into PDF. 

I also want you to know that, I receive no financial compensation from the Connexions 
website even if you purchase the PDF version of the module. 

In the past, unknown individuals have copied my modules from cnx.org, converted them to 
Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither 
receive compensation for those sales nor do I know who does receive compensation. If you 
purchase such a book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior knowledge. 

Affiliation : | am a professor of Computer Information Technology at Austin Community 
College in Austin, TX. 


Complete program listing 


Listing 6 - Servlet01.java. 


Listing 6 - Servlet01.java. 


/*File Servlet01.java, Copyright 1999, R.G.Baldwin 


The purpose of this program is to illustrate a very 
Simple servlet. 


The servlet produces the following text in the browser 
window in large red letters. 


Hello Big Red World 

PRR AR RR Ren RES RAIN RAIN Be Reh RRR ae Ne SIN RC a NI GENIN, BOR TO Ne GN EN Te RI ee ep 
import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 


public class Servlet01 extends HttpServlet{ 
public void doGet(HttpServletRequest req, 
HttpServletResponse res) 
throws ServletException, IOException{ 


//Establish the type of output 
res.setContentType("text/html"); 


//Get an output stream 
Printwriter out = res.getWriter(); 


//Construct an html page to return to the client 
out.printin("<html>"); 
out.printin("<head><title>Servlet01</title></head>"); 
out.printin("<body>"); 


out.printin("<h1i align=\"center\">" 
+"<font color=\"#FFOOOO\">"); 

out.printin( "Hello Big Red World"); 

out.printiln("</font></h1i>") ; 


out.println("</body></html>") ; 


}//end doGet() 
}//end class Servlet01 


-end- 


Java4535r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4535: Introduction to Servlet Code in the Servlets sub-collection. 


Table of Contents 


e Preface 
¢ Questions 
O 1253, 8,50,0; 7,059,100, 11,12, 133.14. 15, 16,17 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4535: Introduction to Servlet Code in the Servlets sub-collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 


to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


Servlets are programming modules that run inside request/response- 
oriented servers, such as Java-enabled web servers, and extend them in 
some manner. 


Go to answer 1 


Question 2 
True or False? 


You can run servlet programs on any server that supports the HTTP 
protocol. 


Go to answer 2 


Question 3 
True or False? 
The use of servlets is restricted to HTTP servers. 


Go to answer 3 


Question 4 
True or False? 


The following import directives, as a minimum, are necessary to support 
servlet programming: 


e import java.io.*; 
e import javax.servlet.*; 
e import javax.servlet.http.*; 


Go to answer 4 


Question 5 
True or False? 


All servlets must implement the JavaServlet interface. You can implement 
it directly. However, it is more common to implement it indirectly by 
extending a class that implements the interface (such as HttpJavaServlet ). 


Go to answer 5 


Question 6 
True or False? 


The Servlet interface declares methods for managing the servlet and its 
communications with clients. You will need to override some or all of those 
methods when you write your servlet. 


Go to answer 6 


Question 7 
True or False? 


Object references of the following types are passed to a servlet when it 
called by a client: 


e JavaServletRequest - encapsulates the communication from the client 
to the server. 

e JavaServletResponse - encapsulates the communication from the 
servlet back to the client 


Go to answer 7 


Question 8 
True or False? 


For an HTTP servlet, the doGet method receives references to two objects 
of the following types as incoming parameters: 


¢ HttpServletRequest 
¢ HttpServietResponse 


Go to answer 8 


Question 9 
True or False? 


A Java-enabled server provide a method to support each of the commands 
that an HTTP client can send to its server. When the server receives a 
command from the client, the corresponding method is called on the servlet. 


As the servlet programmer, you override some or all of those methods to 
provide the desired behavior. 


Go to answer 9 


Question 10 
True or False? 


The doGet method corresponds to the HTTP POST command. If you don't 
override the method, the default implementation reports an HTTP 
BAD_REQUEST error when the browser sends a POST command. 


Go to answer 10 


Question 11 
True or False? 


Overriding the doGet method to support the GET command also 
automatically supports the HTTP HEAD command. 


Go to answer 11 


Question 12 
True or False? 


The fundamental purpose of the GET command makes it possible for the 
client to get something from the server. When you override the doGet 
method, you should, as a minimum: 


e Read data from the request 

e Construct the proper headers in the response 

e Gain access to either the writer or the output stream (depending on 
whether the material to be returned is text or binary data) 

e Write the response data 


Go to answer 12 


Question 13 
True or False? 


The headers that you create in your overridden doGet method should 
include content type and encoding. The content type must be set before the 


writer is accessed. The setContentType method of the response object can 
be called to set the content type. The getWriter method of the response 
object can be called to get access to the output stream. 


Go to answer 13 


Question 14 
True or False? 


The class definition for an HTTP servlet extends the JavaHttpServlet 
class. 


Go to answer 14 


Question 15 
True or False? 


Servlets typically process requests from multiple clients concurrently in a 
multithreaded manner. However, it is possible to write servlets that are 
restricted to single-threaded operation by implementing the 
SingleThreadModel interface. 


Go to answer 15 


Question 16 
True or False? 
When writing a servlet for multi-threaded operation, you should use the 


fewest possible number of instance variables, and synchronize access to 
them if you use them. 


Go to answer 16 


Question 17 
True or False? 


For servlets that extend the HttpServlet class, the following methods may 
be overridden to cause your servlet to interact with the client. 


e doGet - for handling GET, conditional GET and HEAD requests 

¢ doPost - for handling POST requests 

¢ doPut - for handling PUT requests 

¢ doDelete - for handling DELETE requests 

¢ doTerminate - for terminating the servlet and returning control to the 
browser 


Go to answer 17 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


Ea None . Lol] 
Display your nametheke 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


ProbO05a.jpg 
Put your name here 


Answers 


Answer 17 
False. 


For servlets that extend the HttpServlet class, the following four methods 
may be overridden to cause your servlet to interact with the client. 


e doGet - for handling GET, conditional GET and HEAD requests 
e doPost - for handling POST requests 

e doPut - for handling PUT requests 

¢ doDelete - for handling DELETE requests 


Go back to Question 17 


Answer 16 


True. 


Go back to Question 16 


Answer 15 
True. 


Go back to Question 15 


Answer 14 


False. The class definition for an HTTP servlet extends the HttpServlet 
class. 


Go back to Question 14 


Answer 13 
True. 


Go back to Question 13 


Answer 12 


True. 


Go back to Question 12 


Answer 11 


True. 


Go back to Question 11 


Answer 10 


False. The doGet method corresponds to the HTTP GET command. If you 
don't override the method, the default implementation reports an HTTP 
BAD_REQUEST error when the browser sends a GET command. 


Go back to Question 10 


Answer 9 
True. 


Go back to Question 9 


Answer 8 
True. 


Go back to Question 8 


Answer 7 
False. 


Object references of the following types are passed to a servlet when it 
called by a client: 


e ServletRequest - encapsulates the communication from the client to 
the server. 

e ServletResponse - encapsulates the communication from the servlet 
back to the client 


Go back to Question 7 


Answer 6 
True. 


Go back to Question 6 


Answer 5 
False. All servlets must implement the Servlet interface. You can 
implement it directly. However, it is more common to implement it 


indirectly by extending a class that implements the interface (such as 
HttpServlet ). 


Go back to Question 5 


Answer 4 
True. 


Go back to Question 4 


Answer 3 


False. The use of servlets is not restricted to HTTP servers. 


Go back to Question 3 


Answer 2 


False. You must run your servlet under the control of a Java-enabled server 
program. Not all HTTP servers support Java servlets. 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4535r-Review 
e File: Java4535r.htm 

e Published: 03/10/14 

e Revised 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 


should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4550: Session Tracking using Hidden Fields 

The purpose of this module is to explain session tracking using hidden 
fields, and to compare a servlet with a JSP to accomplish the same 
objective. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


o The servlet program 


» Interesting code fragments 
= Tedious and error prone 


o The JSP program 


=» Interesting code fragments 


e Run the programs 
e Miscellaneous 
¢ Complete program listings 


Preface 


This module is one in a collection of modules designed for teaching INE W 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
The purpose of this module is to explain session tracking using hidden 
fields, and to compare a servlet with a JSP to accomplish the same 
objective. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. The servlet user interface at startup. 
e Figure 2. Browser display for Tom, Dick, and Harry. 
e Figure 3. Hidden fields in the servlet output. 


Listings 


e Listing 1. Beginning of the servlet class. 

e Listing 2.. Get and save the hidden values from the browser page. 

e Listing 3. Get and save user input data. 

e Listing 4. Begin constructing the HTML output data. 

e Listing 5. Begin the HTML code for an HTML form. 

e Listing 6. An input field and a submit button. 

¢ Listing 7. Beginning of the list of names. 

e Listing 8. Display the historical data and also save it on the browser. 
e Listing 9. Display most recent value and also store it on the browser. 
e Listing 10. Create basic web page structure. 

e Listing 11. A JSP scriptlet. 

e Listing 12. The body of the for loop. 

e Listing 13 . Another scriptlet. 

e Listing 14. Another JSP expression tag. 

e Listing 15. Terminating scriptlet and HTML code. 

e Listing 16. The servlet program named Java4550a.java. 

e Listing 17. The JSP program named Java4550a.jsp. 


General background information 


A stateless protocol 


The HTTP protocol is a relatively simple request/response protocol that 
does not retain historical information from one client request to the next. In 
other words, each request is a new start insofar as the HTTP server is 
concerned. (HTTP is sometimes referred to as a "stateless" protocol.) 
However, historical information can be very important. The maintenance of 
historical information is often referred to as "session tracking." 


Session tracking 


Session tracking is very important for many web applications including web 
commerce and web games. Therefore, this and the next several modules 
will show you some of the ways that you can accomplish session tracking 
using servlets and JSP. 


Web commerce 


Perhaps the most common example of the need for session tracking is with 
a web commerce application involving a shopping cart. The customer 
(client) downloads various pages from a vendor catalog, selecting items, 
and placing them in a shopping cart. At some point, the customer decides 
either to purchase the items or abandon the shopping trip. 


If the customer decides to purchase the items in the cart, the web 
application must have a record of all the items in the cart. Furthermore, that 
record must be associated with that particular customer so that the sale can 
be consummated. 


Insofar as the HTTP protocol is concerned, each time the customer views a 
different page in the catalog, all information regarding previously viewed 
pages is forgotten. The HTTP protocol doesn't save state information 
regarding an ongoing session by that customer involving multiple pages. It 
is the responsibility of the application to track the session involving that 
client (customer) . 


In the case of the shopping cart application, it is also the responsibility of 
the application to keep track of the items in the cart associated with that 


customer. 
Session tracking using hidden fields 


There are several different ways to accomplish session tracking with a 
servlet. This module will illustrate one of those ways, which is commonly 
known as hidden fields . Other ways will be illustrated in future modules 


Some session tracking schemes maintain historical information over many 
user sessions on a website. Others schemes are more limited. The scheme 
that I will explain in this module is generally limited to one session 
consisting of multiple requests. 


This scheme is probably not useful for large scale web commerce. 
However, it might be useful for an online game where the user makes a 
move and then clicks a submit button. The computer needs to remember 
the entire history of the game, but needn't necessarily remember the history 
if the user leaves the website by closing the browser page. 


A servlet and a JSP 


I will explain two different programs that accomplish the same purpose. 
One of the programs is a servlet. The other program is a JSP. You will see 
that the JSP version is physically easier to write than the servlet version. 
However, you probably need to understand the servlet version in order to 
understand the JSP version. The two also differ in that the servlet is capable 
of determining the name of the server on which it is running but the JSP 
does not have that capability. 


Discussion and sample code 


I will discuss both programs in fragments. A complete listing of the servlet 
program named Java4550a.java is provided in Listing 16. A complete 
listing of the JSP program named Java4550a.jsp is provided in Listing 17 . 


The servlet program 


The program output 


Each time the servlet is called by a browser, it creates and displays an 
HTML form on the browser screen similar to that shown in Figure 1. 


Figure 1 - The servlet user interface at startup. 


[a] Java4550= x 


€- Cf Blocitw = 


Enter a name and press the button 
Name: | 
Submit Name 


Your list of names is: 
Empty 


The HTML form displays: 


e An input text field through which the client can submit a name 
e A submit button 
e A list of previously submitted names 


A new request 


Each time the user clicks the submit button, the contents of the Name field 
are sent to the server and the server views that as a new request. The server 
does not remember historical information from one request to the next. 


However, this servlet provides a mechanism by which a historical list of 
Name values from a sequence of requests is saved and displayed in the area 
identified as Empty in Figure 1. 


Tom, Dick, and Harry 


For example, Figure 2 shows the browser display after the names Tom, 
Dick, and Harry have been sent to the server in three separate requests. 
(Note the list of names near the left-center of Figure 2.) The name Joe has 
been entered into the text field in Figure 2 but the user has not yet clicked 
the submit button to send it to the server. Therefore, that name does not 
appear on the list. 


Figure 2 - Browser display for Tom, Dick, and Harry. 


[ai] Java4550= x 


€¢ > C A Dlocaltsy 


Enter a name and press the button 


Nane: 
Submit Name 


Your list of names is: 
Tom 

Dick 

Harry 


The GET method 


In this servlet, requests are sent from the browser to the server using the 
GET method. (The POST method could also have been used.) Each time the 


browser makes a GET request of the server, an HTML form is created by 
the servlet and sent back to the browser. 


Hidden fields 


Hidden fields are added to the form each time it is created by the servlet. 
One hidden field contains the name submitted for that GET request. Other 
hidden fields contain each of the names submitted by each previous GET 
request during the current session. In other words, the hidden fields on each 
successive form match those of the previous form plus a new hidden field 
for the new name submitted with that GET request. 


Raw HTML code 


Figure 3 shows the HTML code returned to the browser following the 
sending of Tom, Dick, and Harry to the server in three separate requests. 
The three hidden fields are shown at the bottom. 


Figure 3 - Hidden fields in the servlet output. 


) Source of: http:/ /dell8700:8080/Java4550a?firstlame—Harry&item—  lonmaiten 
File Edit View Help 


_=/D) x! 


<html> 

<head><title>Java4550a</title></head> 

<body> 

<form method='get' action="http://del18700:8080/Java4550a"> 
<p>Enter a name and press the button</p> 

<p>Name: <input type="text" name="firstName"/></p> 
<input type="submit" value="Submit Name"/> 

<p>Your list of names is:<br/> 

Tom<br/> 

<input type="hidden” name="item”" value="Tom"> 
Dick<br/> 

<input type="hidden" name="item”" value="Dick"> 
Harry<br/> 

<input type="hidden” name="item”" value="Harry"> 
</form></body></html> 


A: 


The term dell8700 on the fourth line of Figure 3 is the name of the 
computer on which the server that serviced the request was running. 


If the user enters another name into the text field and clicks the submit 
button 


e The new name will be sent to the servlet. 

e This historical data will also be sent to the servlet. 
e The new name will be appended onto the list. 

e The new list will be sent back to the browser. 


Save historical data in an HTML form 


With this approach, the historical data is saved by embedding it in the new 
HTML form that is returned to the browser. There is no requirement to save 
the historical data in a database or in the server's file system. Note however, 
that the data will be lost if the user shuts down the browser or shuts down 
the computer. However, because of the browser cache, it is sometimes 
possible for the user to navigate to other web sites and then return to the 
Same web page using the Back button and find that the historical data is still 
there. 


Simple, reliable, and easy to implement 


This approach has been used by web programmers for many years in those 
cases where it will get the job done. The approach is reliable and easy to 
implement. It places no special requirements on the server software (other 
than the ability to support Java servlets) and it is compatible with all 
browsers that support HTML forms. 


Interesting code fragments 
The doGet method 


The code in Listing 1 shows the beginning of the controlling class and the 
beginning of the doGet method for the servlet. 


Listing 1 - Beginning of the servlet class. 


import java.io.*; 

import javax.servlet.*; 
import javax.servlet.http.*; 
import java.net.*; 


public class Java4550a extends HttpServlet{ 
public void doGet(HttpServletRequest req, 
HttpServletResponse res) 
throws ServletException, 
TOException{ 


//Get and display name of localhost 

InetAddress inetAddress = 
InetAddress.getLocalHost(); 

String hostName = 
inetAddress.getHostName(); 

System.out.println(hostName) ; 


The name of the server 


Without getting into the details as to why, I will tell you that the last three 
lines of code in Listing 1 , (in conjunction with the import directive for 
java.net.* ) cause the name of the computer on which the server is running 
to be saved in the variable named hostName and to be displayed on the 
Tomcat server console. You should have learned enough about the class 
named InetAddress earlier in this course to understand what is going on 
here without further explanation. 


This is very important information for students enrolled in this course 
because this or something like it will be required for many of the 
programming assignments. 


Two incoming parameters 


Recall from previous modules that the doGet method receives two 
parameters. One parameter named req is a reference to an object of the 
interface type HttpServletRequest that contains all of the information sent 
by the browser when the request was made. The other parameter named res 
is areference to an object of the interface type HttpServletResponse that 
collects output information and sends it back to the browser. 


Both of those objects contain numerous methods that can be used to access 
incoming information (req ) or to send information back to the browser ( 
res ) . We will see several of those methods being used shortly. 


Note: A bit of technical trivia: 

HttpServletRequest and HttpServletResponse are interfaces, not classes. 
In general, we don't know the names of the classes from which the objects 
referred to by the incoming parameters were instantiated. And, we don't 
really care because we only plan to call methods on those objects that are 
declared in the interfaces that the objects implement. 

However, just as a matter of technical trivia, it appears that those classes 
have the following names on my system: 


org.apache.catalina.connector.RequestFacade 
org.apache.catalina.connector.ResponseFacade 


Multiple fields with the same name 


An HTML form can have multiple fields with the same name. As you saw 
in Figure 3, the hidden fields are all named item . The code in Listing 2 
calls the getParameterValues method on the request object to get the 
values stored in all of the hidden fields named item . 


Listing 2 - Get and save the hidden values from the browser page. 


String[] items = 
req.getParameterValues("item"); 


The getParameterValues method receives the field name item as a String 
parameter and returns an array of String objects, containing all of the 
values with matching names contained in the request object, or null if the 
field name does not exist. 


Those values are saved in the String array named items shown in Listing 2 
. As you will see later, this is data that was saved from previous requests. 


Get and save user input data 


Listing 3 calls the getParameter method on the request object to get and 
save the value submitted by the browser in the field named firstName . 
(See the input element on the sixth line in Figure 3.) This is also the text 
field shown in Figure 2 . 


Listing 3 - Get and save user input data. 


String name = 
req.getParameter("firstName"); 


The getParameter method receives the name of a request parameter and 
returns the value corresponding to that request parameter as a String , or 


null if the parameter does not exist. (Recall that the data is transmitted to 
the server as name::value pairs.) 


Begin constructing the HTML output data 


At this point in the process, all of the incoming data has been saved in a 
variable named name and an array named items . The time has come to 
construct the raw HTML code and send it back to the client. Listing 4 
begins that process by 


e Telling the browser how to interpret the data ("text/html"). 

e Getting on output stream on the response object on which to print the 
output data. 

e Constructing the first few lines of HTML text. 


Listing 4 - Begin constructing the HTML output data. 


//Establish the type of output 
res.setContentType("text/html"); 


//Get an output stream 
Printwriter out = res.getWriter(); 


//Construct an html form and send it back 
to the client 

out.println("<html>"); 

out.println( "<head> 
<title>Java4550a</title></head>"); 

out.println("<body>"); 


Create raw HTML code for the form 


Listing 5 begins the construction of the HTML form that is to be returned to 
the browser. This code creates the first in a series of HTML statements 
necessary to support the input field and the submit button. (You may need to 
refer to earlier modules that discussed the format of an HTML form in 
order to understand the next few fragments.) 


Listing 5 - Begin the HTML code for an HTML form. 


out.printiln("<form method='get' action=" 
+ "\"http://7" + hostName + 
":8080/Java4550a\">"); 


The code in Listing 5 uses the name of the computer on which the server is 
running ( hostName ) that was obtained and saved earlier to construct the 
action element of the HTML form. This causes the servlet to be suitable for 
running in a server on an computer with any name. It also makes it possible 
to access the servlet from other computers on the local area network 
provided those computers know the name of the computer on which the 
server is running. 


Once again, this is very important information for students enrolled in this 
course. 


This code produced the term dell8700 in Figure 3 because the server was 
running on a computer named dell8700 when the screen shot was taken. 


This fragment results in HTML code that causes a GET request to be sent 
to the HTTP server containing field data as a parameter whenever the user 
presses the submit button 


The input field and the submit button 


Listing 7 places a line of instructional text on the browser screen. 


It also creates the HTML code necessary to place an input field and a 
submit button on the form that will be displayed on the screen as shown in 
Figure 1. 


Listing 6 - An input field and a submit button. 


out.println("<p>Enter a name and press the 
button</p>"); 

out.println("<p>Name: <input type=\"text\" 
name=" 

+ 

"\"firstName\"/></p>"); 

out.printiln("<input type=\"submit\" 
value=" 

+ 

"\"Submit Name\"/>" ) 


The list of names 


Listing 7 provides a line of introductory text for the list of names to be 
displayed on the screen. The first time the form appears on the screen, the 
value stored in the name variable is null, and the word Empty is displayed 
as shown in Figure 1. Later on after multiple requests, the list will be 
populated as shown in Figure 2 . 


Listing 7 - Beginning of the list of names. 


out.println("<p>Your list of names is: 
<br/>"); 
if(name == null){ 
out.printlin("Empty</p>"); 
}//end if 


Create new hidden fields for historical data 


Listing 2 retrieved all of the data in the hidden fields on the form and saved 
that data in a String array named items . 


If that array contains data, the code in Listing 8 performs two actions using 
the data from each of the elements in the array: 


e Display the historical data stored in those element of the array. 
e Create new hidden fields in the HTML output form under construction 
and place the data values from the array in those hidden fields. 


Listing 8 - Display the historical data and also save it on the 
browser. 


Listing 8 - Display the historical data and also save it on the 
browser. 


if(items != null){ 
for(int 1 = 0; i < items.length; it+){ 
//Display names previously saved in 
hidden fields 
out.println(items[i] + "<br/>"); 
//Save the names in hidden fields on 
form currently 
// under construction. 
out.printiln("<input type=\"hidden\" 
name=\"item\" " 
+ "value=\"" + 
items[i] + "\">"); 
}//end for loop 
}//end if 


Limited persistence 


Thus, the historical data is passed forward from the hidden fields of one 
HTML form to the hidden fields of the next HTML form. All of the 
historical data resides on the HTML form in the browser cache in the client 
computer. However, that is not a location that provides long-term 
persistence, so this scheme for session tracking has limited persistence. 


Create new hidden field for new data 


Listing 3 retrieved the field value submitted by the browser and saved that 
value in a variable named name . 


If that variable contains data, the fragment in Listing 9 performs two actions 
using the data stored in the variable. 


e Display the value at the end of the list of names. 


e Create a new hidden field in the HTML output form under 
construction and place the value from the variable in that hidden field. 


Listing 9 - Display most recent value and also store it on the 
browser. 


if(name != null){ 
//Display name submitted with current 
GET request 
out.println(name + "<br/>"); 
//Save name submitted with current GET 
request ina 
// hidden field on the form currently 
under 
// construction 
out.printiln("<input type=\"hidden\" 
name=\"item\" " 
+ "value=\"" + 
name + oY : 
}//end if 


Thus, for each new request by the browser, one additional hidden field is 
added to the HTML form under construction. The new hidden field contains 
the field value submitted by the browser. 


The remaining servlet code 


The remainder of the code for the servlet is typical of what you have seen 
before and can be viewed in the complete listing of the servlet in Listing 16 


Tedious and error prone 


Writing raw HTML code is not fun even under the best of circumstances. 
That is why Iuse a WYSIWYG HTML editor for authoring these modules. 


Even for this very simple servlet, the process of constructing the output 
HTML code using Java println statements was very tedious and error 
prone. Much of the difficulty arises from the fact that Java strings must be 
enclosed in matching double quotes and all HTML attribute values must 
also be enclosed in matching double or single quotes. As you can see from 
Listing 16, the requirement to escape double quotes inside Java strings with 
the backslash character can lead to some very confusing code. (I suppose it 
might be less confusing if I were to use single quotes instead of double 
quotes on HTML attribute values. I will try that in the next module.) 


In any event, the next section presents a JSP version of the same servlet. 
JSP intermingles HTML code with Java code and greatly reduces the 
amount of HTML code that must be constructed using Java println 
statements in a servlet. If you are unfamiliar with JSP, you can learn about it 
in the modules that begin at Java4305: Preface to JSP . 


The JSP program 


A complete listing of the JSP version of this program is provided in Listing 
17.. 1 found this JSP version much easier to write than the servlet version 
discussed above. Admittedly, however, I wrote the servlet version first, so 
that probably helped to make it easier to write the JSP version. 


I wrote all of the HTML code using Microsoft Expression Web 4, which 
provides both aWYSIWYG capability and a raw HTML editing capability. 
Once I confirmed that the HTML code was correct and valid, I went back 
and inserted the JSP tags containing the Java code. 


As mentioned earlier, the JSP does not get and use the name of the 
computer on which it is running. Instead it uses the generic name localhost, 
which limits the ability to access the JSP from another computer on the 
network. 


Interesting code fragments 


Once again, I will discuss this program in fragments. A complete listing of 
the program is provided in Listing 17 . 


Create basic web page structure 


Listing 10 shows the HTML code that is roughly equivalent to the Java 
code in Listing 4 through Listing 7. This code creates the HTML header 
and the basic structure of the web page shown in Figure 1 . 


Listing 10 - Create basic web page structure. 


<html> 
<head><title>Java4550a</title></head> 
<body> 


<form method="get" 

action="http://localhost :8080/Java4550a.jsp"> 
<p>Enter a name and press the button</p> 
<p>Name: <input type="text" name="firstName"/> 
</p> 

<input type="submit" value="Submit Name"/> 
<p>Your list of names is:<br/> 


A JSP scriptlet 


Listing 11 is a scriptlet containing pure Java code. It begins by getting the 
data from the request object. Then it deals with the situation where nothing 
has been entered into the text field in Figure 1, reporting that the list is 
empty. It ends with the beginning of a for loop that is executed when the 


array is not empty. Recall that in JSP, Java code blocks can begin in one 
scriptlet and end in another scriptlet later in the page. That is what is 
happening here. 


Listing 11 - A JSP scriptlet. 


<% 

String[] items = 
request.getParameterValues("item"); 
response.setContentType("text/html"); 


String name = 

request.getParameter("firstName"); 

if(name == null){ 
out.println("Empty"); 

}//end if 


if(items != null){ 


for(int 1 = 0; 1 < items.length; i++){ 
%> 


The body of the for loop 


Listing 12 contains the body of the for loop that began in Listing 11 .. This 
is a combination of a JSP expression tag and raw HTML code to display the 
new value and also to create and populate a hidden field in the output. 


Listing 12 - The body of the for loop. 


<%= items[1i] %> <br/> 
<input type="hidden" name="item" value=" 
<%=items[1]%>"/> 


Another scriptlet 


Listing 13 is another scriptlet containing pure Java code. This scriptlet 
terminates the for loop and the if statement that began in Listing 11 . It also 
begins a new if statement to display the new input value and also to create 
and populate the last hidden field containing the newly received input 
value. 


Listing 13 - Another scriptlet. 


<% 
}//end for loop 
}//end if 


if(name != null){ 
%> 


Another JSP expression tag 


Listing 14 contains another JSP expression tag that displays the new input 
value. Listing 14 also creates and populates the last hidden field with the 
new input value. 


Listing 14 - Another JSP expression tag. 


<%= name %> <br/> 
<input type="hidden" name="item" value=" 
<%=name%>" /> 


Terminating scriptlet and HTML code 


Finally, Listing 15 shows a scriptlet containing a curly bracket to terminate 
the if statement that began in Listing 13 along with raw HTML code to 
terminate the HTML page. 


Listing 15 - Terminating scriptlet and HTML code. 


<% 

}//end if 

%> 
</p></form></body></html> 


Run the programs 


I encourage you to copy the code from Listing 16 and Listing 17 Deploy the 
programs on your own server. Experiment with the code, making changes, 
and observing the results of your changes. Make certain that you can 
explain why your changes behave as they do. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4550: Session Tracking using Hidden Fields 
e File: Java4550.htm 

e Published: 12/22/13 

e Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


Complete program listings 


Listing 16 - The servlet program named Java4550a.java. 


/*File Java4550a.java, Copyright 1999, R.G.Baldwin 
Rev 01/04/14 

The purpose of this program is to illustrate 
session 

tracking through the use of hidden fields. 


Each time the submit button is pressed, this 
servlet 

creates a web page and sends it back to the 
browser. 

The new web page contains the historical data for 
the 

session in hidden fields in the web page. 

The following is a typical web page after the 
names 

Tom, Dick, and Harry have been entered.: 


The program also detects the name of the server 
that it 

is running on and uses that name to construct the 
action 

element of a form. In the output shown below, the 
servlet was running on a computer named dell8700. 


<html> 

<head><title>Java4550a</title></head> 

<body> 

<form method="get" 

action="http://dell18700: 8080/Java4550a"> 
<p>Enter a name and press the button</p> 
<p>Name: <input type="text" name="firstName"/></p> 
<input type="submit" value="Submit Name"/> 
<p>Your list of names is:<br/> 

Tom<br/> 

<input type="hidden" name="item" value="Tom"> 
Dick<br/> 


<input type="hidden" name="item" value="Dick"> 
Harry<br/> 

<input type="hidden" name="item" value="Harry"> 
</form></body></html> 


KKEKEKRKKKKRKRKRKR KEK KRKRKRKR KEKE KERR KEKE KKK KR KEKE KEKE KEKE KERR KR KEKE KKK EEE 


RNR IH Ef, 


import java.io.*; 

import javax.servlet.”*; 
import javax.servlet.http.*; 
import java.net.*; 


public class Java4550a extends HttpServlet{ 
public void doGet(HttpServletRequest req, 
HttpServletResponse res) 
throws ServletException, 
TOException{ 


//Get and display name of localhost 

InetAddress inetAddress = 
InetAddress.getLocalHost(); 

String hostName = inetAddress.getHostName(); 

System.out.println(hostName) ; 


//An array for getting and saving the values 
contained 

// in the hidden fields named item. 

String[] items = 
req.getParameterValues("item"); 


//Get the submitted name for the current GET 
request 
String name = req.getParameter("firstName"); 


//Establish the type of output 
res.setContentType("text/html" ); 


//Get an output stream 
PrintWriter out = res.getWriter(); 


//Construct an html form and send it back to 
the client 

out.printin("<html>"); 

out.printiln("<head><title>Java4550a</title> 
</head>"); 

out.println("<body>"); 


out.println("<form method='get' action=" 
+ "\"http://" + hostName + 
":8080/Java4550a\">"); 


out.println("<p>Enter a name and press the 
button</p>"); 

out.println("<p>Name: <input type=\"text\" 
name=" 

+ 

"\"firstName\"/></p>"); 

out.println("<input type=\"submit\" value=" 

+ "\"Submit 

Name\"/>"); 

out.println("<p>Your list of names is:<br/>"); 

if(name == null){ 

out.println("Empty</p>"); 
}//end if 


if(items != null){ 
for(int 1 = 0; 1 < items.length; it++){ 

//Display names previously saved in hidden 
fields 

out.println(items[i] + "<br/>"); 

//Save the names in hidden fields on form 
currently 

// under construction. 

out.println("<input type=\"hidden\" 


name=\"item\" " 
+ "value=\"" + items[i] 
+ ys" : 
}//end for loop 
}//end if 


if(name != null){ 
//Display name submitted with current GET 
request 
out.println(name + "<br/>"); 
//Save name submitted with current GET 
request ina 
// hidden field on the form currently under 
// construction 
out.println("<input type=\"hidden\" 
name=\"item\" " 
+ "value=\"" + name 
+ iS ; 
}//end if 


out.printin("</form></body></html>" ) ; 


}//end doGet() 
}//end class Java4550a 


Listing 17 - The JSP program named Java4550a.jsp. 


<html> 
<head><title>Java4550a</title></head> 


Listing 17 - The JSP program named Java4550a.jsp. 
<body> 


<form method="get" 

action="http://localhost :8080/Java4550a.jsp"> 
<p>Enter a name and press the button</p> 
<p>Name: <input type="text" name="firstName"/> 
</p> 

<input type="submit" value="Submit Name"/> 
<p>Your list of names is:<br/> 


<% 

String[] items = 
request.getParameterValues("item"); 
response.setContentType("text/html" ); 


String name = 

request.getParameter("firstName"); 

if(name == null){ 
out.println("Empty"); 

}//end if 


if(items != null){ 
for(int 1 = 0; 1 < items.length; it+){ 
%> 
<%= items[1] %> <br/> 
<input type="hidden" name="item" value=" 
<%=1tems[1]%>"/> 
<% 
}//end for loop 
}//end if 


if(name != null){ 

%> 

<%= name %> <br/> 

<input type="hidden" name="item" value=" 


Listing 17 - The JSP program named Java4550a.jsp. 
<%=name%>" /> 

<% 

}//end if 

%> 

</p></form></body></html> 


-end- 


Java4550r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4550: Session Tracking using Hidden Fields in the Servlets sub- 
collection. 


Table of Contents 


e Preface 
e Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INE W 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4550: Session Tracking using Hidden Fields in the Servlets sub- 


collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


The HTTP protocol is a very sophisticated protocol that retains historical 
information from one client request to the next. 


Go to answer 1 


Question 2 
True or False? 


The maintenance of historical information during communications on the 
web is often referred to as "session tracking." 


Go to answer 2 


Question 3 
True or False? 


There are several different ways to accomplish session tracking with a 
servlet. One of those ways is commonly known as hidden fields . 


Go to answer 3 


Question 4 
True or False? 


The hidden fields approach to session tracking has a very long persistence 
(days, months, years) and maintains historical information over many user 
sessions on a website. 


Go to answer 4 


Question 5 
True or False? 


An HTTP server does not remember historical information from one 
request to the next. 


Go to answer 5 


Question 6 
True or False? 


Servlet code can call the getParameter method on the incoming request 
object to get a reference to a String array object containing the String 
values of all incoming hidden fields whose name matches the String passed 
as a parameter to the method. 


Go to answer 6 


Question 7 
True or False? 


Servlet code can call the getParameter method on the incoming request 
object to get a reference to a String object containing the String value of an 
incoming hidden field whose name matches the String passed as a 
parameter to the method. You should only use this method when you are 
sure the parameter has only one value. Otherwise, the results may not be 
what you intended. 


Go to answer 7 


What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None Cox) 


Display your namethiehe. 


iy 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Answers 


Answer 7 
True. 


Go back to Question 7 


Answer 6 


False. Servlet code can call the getParameterValues method on the 
incoming request object to get a reference to a String array object 
containing the String values of all incoming hidden fields whose name 
matches the String passed as a parameter to the method. 


Go back to Question 6 


Answer 5 
True. 


Go back to Question 5 


Answer 4 


False. The hidden fields approach to session tracking is generally limited to 
one session consisting of multiple requests. 


Go back to Question 4 


Answer 3 


True. 


Go back to Question 3 


Answer 2 
True. 


Go back to Question 2 


Answer 1 


False. The HTTP protocol is a relatively simple request/response protocol 
that does not retain historical information from one client request to the 
next. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4550r-Review 
e File: Java4550r.htm 

e Published: 03/10/14 

e Revised 12/26/14 


Note: Disclaimers: 
Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 


possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4560: Session Tracking using URL Rewriting 

The purpose of this module is to explain session tracking using URL 
rewriting, and to compare a servlet with a JSP to accomplish the same 
objective. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


o The servlet program 
» Interesting code fragments 
o The JSP program 
=» Interesting code fragments 
e Run the programs 


e Miscellaneous 
e Complete program listings 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
The purpose of this module is to explain session tracking using URL 
rewriting, and to compare a servlet with a JSP to accomplish the same 
objective. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. The URL for hidden fields. 
e Figure 2. Servlet output screen. 
e Figure 3. HTML code created by servlet. 


Listings 


e Listing 1. Beginning of the doGet method. 

e Listing 2. Get and save URL parameters named item. 

e Listing 3. Construct the new parameter string. 

e Listing 4. Concatenate current date and time to new parameter string. 
e Listing 5. Begin creation of the HTML page. 

e Listing 6. Construct the hyperlink. 

e Listing 7. Introductory text. 

e Listing 8. Display date and time history. 

e Listing 9. Display the current date and time. 

e Listing 10. Import necessary packages. 

e Listing 11. Get data from the old parameter string. 

e Listing 12 . Construct a new parameter string. 

e Listing 13. Concatenate current date and time to the parameter string. 
e Listing 14. Create the hyperlink. 

e Listing 15. Display the list of dates. 

e Listing 16. The servlet named Java4560a.java 

e Listing 17. The JSP program named Java4560b.jsp. 


General background information 


A stateless protocol 


You learned in earlier modules that the HTTP protocol is a relatively simple 
request/response protocol that does not retain historical information from 
one client request to the next. You also learned that historical information 
can be very important, and the maintenance of historical information is 
often referred to as "session tracking." 


Session tracking 


Because session tracking is very important for many web applications, an 
earlier module along with this and the next several modules will show you 
some of the ways that you can accomplish session tracking using servlets 
and JSP. 


Session tracking using URL rewriting 


There are several different ways to accomplish session tracking with a 
servlet. The earlier module explained session tracking using hidden fields. 
This module will illustrate how to accomplish session tracking using URL 
rewriting. 


Limited persistence 


You learned in the earlier module that the session tracking scheme using 
hidden fields is generally limited to one session consisting of multiple 
requests. You also learned that the scheme is probably not useful for large 
scale web commerce. However, it might be useful for an online game where 
the user makes a move and then clicks a submit button. The computer 
needs to remember the entire history of the game, but needn't necessarily 
remember the history if the user leaves the website by closing the browser 


page. 


The same holds true for session tracking using URL rewriting. Session 
tracking using URL rewriting provides only limited persistence. While this 
may seem like a major downside, there is at least one upside for both 
schemes. 


Comparison with cookies 


A future module will explain session tracking using cookies. Cookies 
probably provide the most commonly used scheme for session tracking 
because cookies can provide persistence over long periods of time. 
However, there is also a downside to cookies. The user can disable cookies 
in the browser, which completely defeats the use of cookies for session 
tracking. 


Therefore, if your online game uses cookies for session tracking and the 
user disables cookies, then you game won't work in that browser. As far as I 
know, it is not possible for the user to prevent session tracking using either 
hidden fields or URL rewriting. 


A servlet and a JSP 


I will explain two different programs that accomplish the same objective in 
this module. One of the programs is a servlet. The other program is a JSP. 
You probably need to understand the servlet version in order to really 
understand the JSP version. 


The URL window with hidden fields 


If you observed the URL window in your browser while running the 
hidden-field servlet in the earlier module , you probably noticed that after 
several cycles, the window containing the URL looked something like 
Figure 1. 


Figure 1 - The URL for hidden fields. 


http: //localhost:8080/Java4550a?firstName=Harryéitem=Toméitem=Dick 


What you see in Figure 1 is the standard way that HTML forms pass 
parameters to their HTTP servers using the GET method. 


A parameter string 


When the user clicks the submit button, a string containing the names and 
values (name: :value pairs again) for all of the fields is created and 
concatenated onto the URL. The string of parameter values is joined to the 
URL with a"?" character. The individual parameters are separated from one 
another with the ampersand character. 


Recall that for the servlet in the earlier module , the field named firstName 
was the visible field in which the user entered a name. The fields named 
item were hidden fields that were created and populated with historical data 
when the servlet generated the HTML form for return to the client. You can 
see parameters with both of these names in Figure 1. 


The parameters are accessible by the servlet 


It doesn't really matter how these parameter names and values come to be 
concatenated onto the URL. As far as the servlet is concerned, their values 
are accessible using the methods getParameter() and 
getParameterValues() . 


This suggests that in some cases, it might be beneficial for the servlet to 
save the historical data by concatenating it onto a URL referenced in the 
HTML page before returning the page to the client. That is one of the ways 
that URL rewriting can be used to implement session tracking. 


Discussion and sample code 


As I mentioned earlier, I will present a servlet and a JSP program where 
both are designed to achieve the same objective. This will make it possible 
for you to compare the two programming styles. 


Both programs are designed to illustrate the concept of URL rewriting and 
are not intended to have any practical value in their own right. 


I will explain both programs in fragments. A complete listing of the servlet 
named Java4560.java is provided in Listing 16. A complete listing of the 
JSP program named Java4560b.jsp is provided in Listing 17 . 


The servlet program 


The servlet named Java4560a.java illustrates session tracking using URL 
rewriting. In this servlet, parameters containing the historical data are added 
to the servlet's URL each time the servlet generates anew HTML page. The 
updated URL is included as a hyperlink in the new web page. 


The servlet output 


Each time the servlet is called, it creates and displays an HTML page on the 
client screen similar to that shown in Figure 2. 


Figure 2 - Servlet output screen. 


[ae] Java4560- x 
€ > CG ft Dlocaltsy 


Click Here 


Your list of times is: 

Sun Dec 22 21:57:55 CST 2013 
Sun Dec 22 21:58:01 CST 2013 
Sun Dec 22 21:58:02 CST 2013 
Sun Dec 22 21:58:38 CST 2013 


The page displays: 


e A hyperlink to the servlet URL labeled Click Here 
e A list of the dates and times on which the user previously called the 
servlet by clicking on the hyperlink. 


A get request 


Each time the user clicks the hyperlink, the client sends a GET request to 
the server. The GET request calls the servlet, which determines the current 
date and time in milliseconds relative to January 1, 1970. An HTML page is 
created and sent back to the client. 


Update the parameter string 


The current date and time in milliseconds is added as a parameter named 
item to the servlet URL referenced by the hyperlink in the newly-created 
HTML page. In addition to the current date and time, the values of the 
previous dates and times on which the user called the servlet are retrieved 
from the incoming URL parameter string and appended to the new URL 
parameter string. 


In other words, the parameter string values for each successive URL that is 
generated match those of the previous URL. In addition, a new parameter 
value is added that represents the current date and time. 


Embed historical data in the web page 


In a manner similar to session tracking using hidden fields, the historical 
data is saved by embedding it in the new HTML page that is returned to the 
client. There is no requirement to save the historical data in a database or in 
the server's file system. 


Figure 3 shows the HTML source code that corresponds to the web page 
shown in Figure 2 . 


Figure 3 - HTML code created by servlet. 


view-source:localhost:808 x 


- > C A&B view-source:localhost:8080/Java4560a?it ¥ 


1| <html> 

2| <head><title>Java4560a</title></head> 

3| <body> 
<a href="http://localhost:8080/Java4560a? 
item=1387771075185éitem=1387771081455éitem=1387771082522¢ 
item=1387771118708'>Click Here</a> 

§|<br/><br/>Your list of times is:<br/> 

6}Sun Dec 22 21:57:55 CST 2013<br/> 

7;}Sun Dec 22 21:58:01 CST 2013<br/> 

8|Sun Dec 22 21:58:02 CST 2013<br/> 
Sun Dec 22 21:58:38 CST 2013<br/> 

10| </body></html> 


The URL parameter string 


The most interesting thing in Figure 3 is the content of Line 4. (Note that 
Line 4 is wrapped and appears as three physical lines in Figure 3.) Each 
large numeric value that you see in Line 4 is the number of milliseconds 
since January 1, 1970 for a particular date and time. These values in 
milliseconds are translated into actual dates and times and shown in Lines 6 
through 9. 


No special software requirements 


This approach places no special requirements on the server software other 
than the ability to support Java servlets. The approach should be compatible 
with all browsers that support hyperlinks. 


Interesting code fragments 
Beginning of the doGet method 


As mentioned earlier, I will explain this program in fragments. Listing 1 
shows the beginning of the controlling class and the beginning of the doGet 
method. You have seen code like this before, so I won't discuss it further. 


Listing 1 - Beginning of the doGet method. 


import java.io.*; 

import java.util.*; 

import javax.servlet.*; 
import javax.servlet.http.*; 


public class Java4560a extends HttpServlet{ 
public void doGet(HttpServletRequest 
request, 
HttpServletResponse 
response) 
throws ServletException, 
IOException{ 


Get and save URL parameters named item 


An HTTP URL can have multiple parameters with the same name. In this 
case, all of the parameters are named item . Listing 2 gets the values stored 
in all of the parameters named item and saves them in a String array named 
items . 


(Each time the servlet is called, the size of the list of parameters increases 
by one.) 


The fragment also instantiates and initializes a String object used later to 
construct a new parameter string for the URL. 


Listing 2 - Get and save URL parameters named item. 


Listing 2 - Get and save URL parameters named item. 


String parameters = "?"; 
String[] items = 
request.getParameterValues("item"); 


Construct the new parameter string 


Listing 3 uses the parameter values from the old parameter string to 
construct a new parameter string. The new parameter string will later be 
concatenated to the URL for the servlet. 


Listing 3 - Construct the new parameter string. 


if(items != null) { 
for(int i = 0; i < items.length; i++){ 
parameters = parameters + "item=" + items[i] + "&"; 
}//end for loop 
}//end if 


Concatenate current date and time to new parameter string 


Listing 4 gets the current date and time in milliseconds and saves it in a 
long variable named theDate . Then it concatenates the current date and 
time in milliseconds onto the new parameter string that was constructed in 
Listing 3 . 


Listing 4 - Concatenate current date and time to new parameter 
string. 


Listing 4 - Concatenate current date and time to new parameter 
string. 


long theDate = new Date().getTime(); 
parameters = parameters + "item=" + 
theDate; 


Begin creation of the HTML page 


Listing 5 begins the creation of the output HTML page. You have seen code 
like this before, so I won't discuss it further at this point. 


Listing 5 - Begin creation of the HTML page. 


//Establish the type of output 
response.setContentType("text/html"); 


//Get an output stream 
Printwriter out = response.getWriter(); 


//Construct an HTML page and send it back 
to the client 

out.println("<html>"); 

out.println("<head> 
<title>Java4560a</title></head>"); 

out.println("<body>"); 


Construct the new hyperlink 


Listing 6 constructs the hyperlink containing the URL for the servlet. Note 
that the hyperlink references a URL that includes the parameter string 
constructed above. 


If you compile and run this servlet, you may need to substitute the name of 
your server in place of my server. 


Listing 6 - Construct the hyperlink. 


out.println("<a 
href='http://localhost:8080/Java4560a" 
+ parameters + 

"">Click Here</a>" ) 


Introductory text 


Listing 7 provides a line of introductory text for the list of dates and times 
to be displayed on the screen. 


Listing 7 - Introductory text. 


out.println("<br/><br/>Your list of times 
is:<br/>"); 


Display date and time history 


Listing 2 retrieved all of the data in the incoming URL parameters and 
saved that data in a String array named items . 


If that array contains data, Listing 8 displays the date and time for each 
element in the array. 


The parameter values in milliseconds are first converted from String to 
long . Each of the long values is then used to instantiate a new Date object, 
which is displayed in the format shown in Figure 2 . 


Listing 8 - Display date and time history. 


if(items != null){ 
for(int 1 = 0; i < items.length; i++){ 
long millis = 
Long.parseLong(items[i]); 
out.println("" + new Date(millis) + " 
<br/>"); 
}//end for loop 
}//end if 


(Hopefully you already understand the relationship between the 
overridden toString method of the Date class and the format 
resulting from passing a Date object's reference to the printIn 
method. If not, see ApOO05: Preface to OOP Self-Assessment and 
the modules following that one.) 


Display the current date and time 


Listing 4 obtained the current date and time in milliseconds and saved it in 
a variable named theDate . Listing 9 uses that value to instantiate and 
display a new Date object reflecting the current date and time. 


Listing 9 - Display the current date and time. 


out.printin("" + new Date(theDate) + " 
<br/>"); 

out.println("</body></html>");//finish 
HTML page 


Listing 9 also creates the HTML code necessary to finish the HTML page. 


The JSP program 


I will also discuss the JSP program named Java4560b.jsp in fragments. A 
complete listing of the program is provided in Listing 17 . 


Interesting code fragments 
Import necessary packages 


Listing 10 shows the necessary import directives plus the beginning of the 
HTML page. 


Listing 10 - Import necessary packages. 


<%@ page import='java.util.*,java.io.*' %> 


<html> 
<head><title>Java4560b</title></head> 
<body> 


There's nothing new in Listing 10 with the possible exception of the format 
of the import directives. The format is different from the format used in 
regular Java code. (See Listing 1 .) 


Some packages are imported automatically 


Recall from Java4307: Servlets and JSP that it is not necessary to import 
javax.servlet and javax.servlet.http . Those two packages are 
automatically imported by the JSP container on the server. No page 
directive import settings are required for using the classes defined in these 
packages. 


Get data from the old parameter string 


Listing 11 shows the beginning of a scriptlet containing pure Java code. 


Listing 11 - Get data from the old parameter string. 


Listing 11 - Get data from the old parameter string. 


<% 
String parameters = "?"; 
String[] items = 
request.getParameterValues("item"); 


The code in Listing 11 declares and initializes a String that will be used 
later to construct a new parameter string. 


Listing 11 also gets and saves the values of all of the parameters from the 
old parameter string named "item" . 


Construct a new parameter string 


Listing 12 constructs a new parameter string containing the names and 
values of all the parameters named "item" in the old parameter string. (A 
parameter for the current date and time will be concatenated later.) 


Listing 12 - Construct a new parameter string. 


if(items != null){ 
for(int i = 0; i < items.length; i++){ 
parameters = parameters + "item=" + items[i] + "&"; 
}//end for loop 
}//end if 


Concatenate current date and time to the parameter string 


Listing 13 gets the current date and time in milliseconds and concatenates it 
to the new parameter string with the name "item" . 


Listing 13 - Concatenate current date and time to the parameter 
string. 


long theDate = new Date().getTime(); 
parameters = parameters + "item=" + 
theDate; 


response.setContentType("text/html"); 
> 


Listing 13 also sets the output content type to "text/html" . 


Finally, Listing 13 signals the end of the scriptlet that began in Listing 11 . 
Create the hyperlink 


Listing 14 uses a JSP expression tag along with raw HTML code to create 
the hyperlink shown near the top of the page in Figure 2 . 


Listing 14 - Create the hyperlink. 


<a href="http://localhost:8080/Java4560b. jsp<t=parameters%>'> 
Click Here</a> 


&<br/><br/>Your list of times is:<br/> 


Listing 14 also uses raw HTML code to create the line of text that appears 
immediately above the list of dates in Figure 2 . 


Display the list of dates 


Listing 15 shows another scriptlet containing pure Java code. The first six 
lines of code display the historical date and time information. The next line 
of code displays the current date and time. 


Listing 15 - Display the list of dates. 


<% 
if(items != null){ 
for(int 1 = 0; 1 < items.length; it++){ 
long millis = 
Long.parseLong(items[i]); 
out.println("" + new Date(millis) + " 
<br/>"); 
}//end for loop 
}//end if 


out.println("" + new Date(theDate) + " 
<br/>"); 

out.println("</body></html>"); 
> 


The last line of code creates the HTML elements necessary to finish the 
page. 


A choice 


I could have broken this scriptlet into two or more scriptlets using raw 
HTML code in between to display the material. However, I decided that it 
was simpler in this case to use Java println statements to display the 
material than it would have been to break it up and use interspersed HTML 
code. 


Run the programs 


I encourage you to copy the code from Listing 16 and Listing 17 . Install 
the programs on your server and run them. Experiment with the code, 
making changes, and observing the results of your changes. Make certain 
that you can explain why your changes behave as they do. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4560: Session Tracking using URL Rewriting 
e File: Java4560.htm 

e Published: 12/23/13 

e Revised: 01/31/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


Complete program listings 


I recognize that the code in Listing 16 may be difficult to read. Note, 
however that if you have difficulty reading it, you can reconstruct the entire 
program from the code fragments provided earlier. You might also try 
zooming with your browser to see if that makes it easier to read. 


Listing 16 - The servlet named Java4560a.java. 


/*Pile JavadS60a.java, Copyright 1999, R.G.Baldwin 
Rev 12/22/13 


The purpose of this program is to illustrate session 
tracking through the use of rewritten URLs 
AHAABAABAAAAAAAAAAAAAAAAAAAAMAAARAABAARAAAA AAA AABAABA AAA! 
import java.io.+; 

import java.util.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 


public class JavadS60a extends HttpServlet( 
public void doGet (HttpServletRequest request, 
RetpServletResponse response) 
throws ServletException, I0Exception( 


//Ref variable used to construct the parameter string 
String parameters = "2"; 


//’n array for getting and saving the values contained 
// in the parameters named iten. 
String[] items = request.getParaneterValues("iten"); 


if(items != null) ( 
for(int i = 0; i < items.length: i+) ( 
//Aecess the old parameter string to construct the 
// new parameter string to append to the URL below. 
parameters = parameters + “item=" + items[i] + "é"; 
}//end for loop 
MJend if 


//Get the current date and time in milliseconds. Add 
// the current date and tine to the parameter string 
// constructed above. 

long theDate = new Date() .getTine(); 

parameters = parameters + “iten=" + theDate: 


//Establish the type of output 
response. setContentT ype |"text/htal") + 


//Get an output stream 
Printiiriter out = response.getiriter(); 


//Construct an IML page and send it back to the client 
out.println("<htal>"); 
out.println|"<head><titlenava4S6la</titled</head>") 
out.println ("<body>") + 


//Construct the hyperlink referencing the servlet here. 
//} Mote that the hyperlink references a URL that 
// includes the parameter string constructed above. 


//Substitute the name of your server here 
out.println("<a href="http://localhost:8080/Java4560a" 
+ parameters + "'>Click Here</a>"); 


//Display the historical data stored in the parameter 
/} string. 
out.println("<br/><br/>Your list of times is:<br/>"); 


if(items != null) ( 
for(int i = 0; i < items.length: itt) ( 
//Convert from milliseconds as a String to a Date 
// object. Then format for display. 
long nillis = Long.parseLong(itens[i]); 
out.println("" + new Date(millis) + "<br/>"; 
Mend for loop 
V/lend if 


//Convert from milliseconds to a Date object and then 
/} format for display. 

out.println("" + new Date(theDate) + "<br/>"); 
out.println("</body></html>");//finish ETML page 


Mend doGet() 
Hiend class Java45é0a 


Listing 17 - The JSP program named Java4560b. jsp. 


<$@ page import='java.util.*,java.io.*' %> 


<html> 
<head><title>Java4560b</title></head> 
<body> 


<3 
String parameters = "2"; 
String[] items = request.getParameterValues ("item") ; 


if(items != null){ 
for(int i = 0; i < items.length; it+){ 
parameters = parameters + "item=" + items[i] + "&"; 
}//end for loop 
}//end if 


long theDate = new Date().getTime(); 
parameters = parameters + "item=" + theDate; 


response. setContentType ("text/html") ; 
$> 


<a href="http://localhost:8080/Java4560b. jsp<=parameters$>'> 
Click Here</a> 


<br/><br/>Your list of times is:<br/> 


<3 
if(items != null){ 
for(int i = 0; i < items.length; i++) { 
long millis = Long.parseLong(items[i]); 
out.println("" + new Date(millis) + "<br/>"); 
}//end for loop 
}//end if 


out.printin("" + new Date(theDate) + "<br/>"); 
out.println("</body></htm1>") ; 


Java4570: Session Tracking using Cookies 
The purpose of this module is to explain session tracking using cookies, and 
to compare a servlet with a JSP to accomplish the same objective. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


¢ General background information 
o Program output 
o What are cookies? 


o The Java Cookie class 


e Discussion and sample code 


o The servlet program 
= Interesting code fragments 
o The JSP program 
e Run the programs 


e Miscellaneous 
¢ Complete program listing 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
The purpose of this module is to explain session tracking using cookies, and 
to compare a servlet with a JSP to accomplish the same objective. 


If you haven't already done so, I strongly recommend that you study 
Java4370: Cookies with JSP before continuing with this module. Dr. 
Martinez explains many aspects of cookies in that module. Most of those 
aspects apply to both JSP and servlets and many of them won't be repeated 
in this module. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Output from the servlet program. 
e Figure 2. Output from the JSP program. 
e Figure 3. Description of the Cookie constructor. 


Listings 


e Listing 1. Beginning of the doGet method. 

e Listing 2. Construct a unique session ID. 

e Listing 3. Get all of the cookies into an array of type Cookie. 
e Listing 4. Get and save submitted value. 

e Listing 5. Create a new session ID cookie. 

e Listing 6. Create, name, and populate a new Cookie object. 
e Listing 7. Familiar code. 

e Listing 8. Get and display cookie names and values. 

e Listing 9 . Display currently submitted field value. 

e Listing 10. The servlet program named Java4570a.java. 

e Listing 11. The JSP program named Java4570b.jsp. 


General background information 


Program output 


I will explain a servlet program and present a comparable JSP program in 
this module. The purpose is to show you how to write servlets that use 
cookies for session tracking and to make it possible to compare a servlet 
and a JSP that both achieve the same objective. 


The servlet output 


Figure 1 shows the output produced by requesting the servlet from the 
localhost server using the Chrome browser and then submitting the names 
Tom, Dick, and Harry using the input text field and the submit button. I will 
refer back to this Figure later while explaining the servlet code. 


Figure 1 - Output from the servlet program. 


[ae] Java4570a 


€ => CG ff BD localhost:8080/Java4570a?firstNar 22 


Enter a name and press the button 


Name: | 
Submit Name 


Your session ID and list of names is: 

session] D:-6£29892%3A1432599a8cc%3A-Tife 
1387909918280:Tom 

1387909927784-Dick 

Harry 


The JSP output 


Figure 2 shows the output produced by requesting the JSP from the 
localhost server using the Firefox browser and then submitting the names 
Tom, Dick, and Harry using the input text field and the submit button. I will 
refer back to this Figure later while explaining the JSP code. 


Figure 2 - Output from the JSP program. 


) Java4570b - Mozilla Firefox 


Ley ee 
mple | i: Template 
LE jsessior P| & FF 


€& @ localhost:3080/Java4570b. jsp7fi 


@ Share Browser WebEx” 


Enter a name and press the button 
Name: 
Submit Name | 


Your session ID and list of names 1s: 
JSESSIONID:7822176275F9F9C8E2FSFEBEF75A1655 
sessionID:-1b003acb%3A14325b20d6e%3A-7 fff 
1387909983838:Tom 

1387909996183-Dick 


Harry 


(The main difference between Figure 1 and Figure 2 is the line that begins 
with JSESSIONID in Figure 2. Also Figure 1 is displayed in a Chrome 
browser and Figure 2 is displayed in a Firefox browser.) 


What are cookies? 


Cookies are information that is created by a web application and stored on 
the client machine by the browser. Under certain conditions, this 


information is sent to the HTTP server whenever a request is sent from the 
client to the server. 


Used for session tracking 


Cookies are widely used by various server-side programming techniques for 


session tracking. Java provides classes and methods designed to allow you 
to use cookies in your servlets. 


Which server receives a cookie? 


By default, cookies are sent only to the host that caused them to be saved. 
Methods can be called to set attributes for each cookie that determine which 
servers will receive the cookie. For example, the setDomain method can be 
used to specify a domain pattern indicating which servers should receive a 
cookie. 


By default, cookies are sent to the page that set the cookie and to all the 
pages in that directory or under that directory. This also can be modified by 
calling the setPath method on the cookie. 


What is the life expectancy of a cookie? 


Also by default, a cookie expires when the browser exits. The setMaxAge 
method can be called to override the default and specify the maximum age 
of the cookie in seconds. The cookie will expire when the maximum age 
has been reached. The parameter to this method is an int so the maximum 
age of a cookie can be a very large number of seconds. (The maximum 
positive value of Java type int is 2,147,483,647. If I did the arithmetic 
correctly, that is about 68 years.) 


Comments in a cookie 


The setComment method can be used to provide a comment with the 
cookie. The browser may elect to make this information available to the 
user. 


Name and value of a cookie 


The constructor sets the name and value of a cookie when the Cookie 
object is instantiated. The setValue method can be used to assign a new 
value to the cookie after it is instantiated. 


Other attributes 


There are a few other attributes that can be set as well. You can read about 
them in the Java(TM) EE 7 documentation. 


Cookies can be disabled 


CAUTION: The user can disable cookies in most, and perhaps all browsers. 
As a result, the user can defeat session tracking using cookies. 


Therefore, unless you can be certain that all of your clients will operate 
with cookies enabled, the use of cookies for session tracking may not be 
satisfactory in all cases. (The fallback position may be the less-persistent 
Hidden Fields and/or URL Rewriting methods of session tracking.) 


The Java Cookie class 


The Cookie class represents a cookie that can be used for session 
management with the HTTP protocol. 


Cookies are used to cause user agents such as web browsers to store small 
amounts of state associated with a user's web browsing activities. 


Applications 
Common applications for cookies include: 


e Storing user preferences 
e Automating low security user signon facilities, and 
e Helping collect data used for "shopping cart" applications. 


Names, values, and attributes 


Each cookie has a name and a single value (a name::value pair) . As 
mentioned earlier, it may have optional attributes, including: 


e A comment presented to the user 

Path and domain qualifiers to specify which hosts can see the cookie 
e A maximum age, and 

e A version. 


Sending cookies to the browser 


In the Java API, cookies are saved one at a time into such HTTP response 
headers, using the addCookie method. 


According to the Java documentation , The browser is expected to support 
20 cookies for each web server, 300 cookies total, and may limit cookie size 
to 4 KB each. 


Servers assign cookies, using fields added to HTTP response headers. 
Retrieving cookies from the browser 


Cookies are passed from the browser to the server using fields added to 
HTTP request headers. 


In the Java API, HTTP cookies are retrieved using the getCookies method. 
This method returns all of the cookies found in the request sent by the 
client. 


Description of the Cookie constructor 


An abbreviated description of the constructor for the Cookie class is shown 
in Figure 3 . 


Figure 3 - Description of the Cookie constructor. 


Figure 3 - Description of the Cookie constructor. 


public Cookie(String name, String value) 
Constructs a cookie with the specified name and value. 


The name of a cookie cannot be changed once the cookie has been 
created. 


The value can be anything the server chooses to send. The cookie's 
value can be changed after creation with the setValue method. 


Parameters: 


e name - the name of the cookie 
e value - the value of the cookie 


Discussion and sample code 


The servlet program 


The name of the servlet program is Java4570 I will discuss this program in 
fragments. A complete listing of the program is provided in Listing 10 . 


Displays an HTML form 


Each time the servlet is called, it displays an HTML form on the client 
screen as shown in Figure 1. The form contains: 


e An input field for submitting a name 
e A submit button 
e A list of previously submitted names 
e Some Static text 


A unique session ID 


The first time the servlet is called by a given browser, code written into the 
servlet creates a unique session ID and stores it in a cookie on the browser. 
This session ID is not used for any purpose in this sample program. It is 
included in the servlet simply to show how to create and save a unique 
session ID. 


A cookie containing the submitted value 


Each time the servlet is called, it creates a cookie containing the field value 
submitted by the user and stores it on the browser. 


When the servlet is called, it gets all of the cookie information stored on the 
browser and displays that information on the client screen as shown in 
Figure 1. The display includes the unique session ID and all of the field 
values submitted by the user during that session. 


The maximum age of the cookies 
The cookie containing the session ID is deleted when the browser is exited. 


The maximum age for all of the other cookies is set to 60 seconds. 
Therefore, if you submit some names, wait more than 60 seconds, and then 
submit some more names, the first batch of names submitted will have 
expired and will have disappeared from the list. 


The lifetime of a session 


A session doesn't end just because the user visits another page. If the user 
returns to the Java4570 servlet without exiting the browser, the cookies 
written by Java4570 that have not yet expired will continue to exist on the 
browser and the session will continue. 


Also, if the user exits and then restarts the browser and calls the servlet, the 
cookies that have not yet expired will continue to exist and will be 
displayed when the server responds to the request. Thus, a session being 
tracked by cookies with a long maximum age can persist over long periods 
of time, even when the computer has been shut down and restarted. (Many 


web sites will remember you on the same computer using the same browser 
over days, months, and even years.) 


Interesting code fragments 
Beginning of the doGet method 


Listing 1 shows the beginning of the controlling class and the beginning of 
the doGet method. You have seen code like this before, so I won't discuss it 
further in this module. 


Listing 1 - Beginning of the doGet method. 


public class Java4570a extends HttpServlet{ 
public void doGet(HttpServletRequest 
request, 
HttpServletResponse 
response) 
throws ServletException, 
IOException{ 


Construct a unique session ID 


Listing 2 constructs a unique session ID that is later written into a cookie on 
the browser. 


Listing 2 - Construct a unique session ID. 


String uid = new 
java.rmi.server.UID().toString(); 

String sessionID = 
java.net.URLEncoder .encode(uid) ; 


A UID object 


The first step is to get a String representation of a UID object. According to 
the documentation, the UID class is an "Abstraction for creating identifiers 
that are unique with respect to the host on which it is generated." 


Some cleanup is required 


The second step is to call the encode method of the URLEncoder class to 
convert the string into a MIME format called the "x-www-form-urlencoded" 
format. This ensures that the identifier can be reliably transmitted between 
the server and the client and that it will contain only those characters that 
are acceptable for saving in a cookie (see documentation on the setValue 
method of the Cookie class for more information) . 


To convert the String , each character is examined and modified as follows: 


e The ASCII characters ‘a’ through 'z', 'A' through 'Z', and '0' through '9' 
remain the same. 

e The space character is converted into a plus sign '+'. 

e All other characters are converted into the 3-character string "%xy", 
where xy is the two-digit hexadecimal representation of the lower 8- 
bits of the character. 


A typical session identifier created by this process might appear as follows: 


1cce64%3Ad69878ccf0%3A-7ff9 


Get all of the cookies into an array of type Cookie 


Listing 3 calls the getCookies method of the incoming 
HttpServietRequest object to get and save the cookies submitted by the 
browser. The values of the cookies will be displayed later. 


Listing 3 - Get all of the cookies into an array of type Cookie. 


Cookie[] cookies = request.getCookies(); 


Get and save submitted value 


As in the sample programs in earlier modules, Listing 4 gets and saves the 
field value submitted by the client. 


Listing 4 - Get and save submitted value. 


String name = 
request.getParameter("firstName"); 
response.setContentType("text/html"); 


Listing 4 also establishes the type of output. 


Create a new session ID cookie 


Because cookies are sent to the browser using HTTP headers, they should 
be added to the response before you send any content. 


If no cookies were submitted by the client with the request, this is 
interpreted by this servlet to be the beginning of the session. A new Cookie 
object is instantiated containing the session ID value created above along 
with the name of the cookie: sessionID . 


Then the cookie is sent to the client's browser by calling the addCookie 
method on the outgoing HttpServletResponse object as shown in Listing 5 


Listing 5 - Create a new session ID cookie. 


if(cookies == null){ 
Cookie newCookie = new 
Cookie("sessionID",sessionID); 
response.addCookie(newCookie) ; 
}//end if 


PrintWriter out = response.getWriter(); 


Listing 5 also gets an output stream using code that you have seen in earlier 
modules. 


Create, name, and populate a new Cookie object 


Listing 6 instantiates a Cookie object containing the field value submitted 
by the client and sends that cookie back to the browser for storage. 


Listing 6 - Create, name, and populate a new Cookie object. 


if(name != null){ 
String cookieName = "" + new 
Date().getTime(); 
Cookie newCookie = new 
Cookie(cookieName, name); 
newCookie.setMaxAge(60) ; 
response.addCookie(newCookie) ; 
}//end if 


Unique names for cookies 


Unless delineated by path information, each cookie needs a unique name in 
addition to its value. Assuming that successive calls to this servlet will be 
separated in time by at least one millisecond, unique names can be created 
by using the current date and time in milliseconds. That mechanism was 
used in Listing 6 to create unique cookie names. The getTime method of 
the Date class returns the date and time in milliseconds represented by a 
Date object. The Date object in Listing 6 encapsulates the current date and 
time. You can see those times represented in milliseconds in the list of 
cookies in Figure 1. 


On the other hand, a servlet that creates two or more Cookie objects could 
easily create more than one cookie during each one-millisecond interval. In 


that case, you should probably use something like the code in Listing 2 to 
create unique cookie names. 


Familiar code 


Listing 7 contains code that is very similar to code discussed in earlier 
modules, so I won't discuss it further here. The fragment is being included 
here for continuity. 


Listing 7 - Familiar code. 


Listing 7 - Familiar code. 


//Construct an html form and send it back 
to the client 

out.println("<html>"); 

out.println("<head> 
<title>Java4570a</title></head>"); 

out.println("<body>"); 


//Substitute the name of your server in 

// the following statement. 

out.println("<form method='get' action=" 

+ 

"'http://localhost:8080/Java4570a'>"); 

out.println("<p>Enter a name and press the 
button</p>"); 

out.println("<p>Name: <input type='text' 
name=" 

+ 

"'firstName'/></p>"); 

out.println("<input type='submit' value=" 

+ 

"'Submit Name'/>"); 

out .println( 

"<br/><br/>Your session ID and list of 

names 1is:<br/>"); 

if(name == null){ 

out.println("Empty<br/>"); 
}//end if 


Get and display cookie names and values 


Listing 8 calls the getName and getValue methods of the Cookie class to 
get and display the names and values of each of the cookies saved earlier in 
the array of cookies. 


The first value displayed should be the session ID that was stored in the 
first cookie saved. The remaining items in the list should be the field input 
values previously submitted by the user each time the servlet was called but 
not including the field input value for this invocation of the servlet. 


Listing 8 - Get and display cookie names and values. 


if(cookies != null){ 
for(int 1 = 0; 1 < cookies.length; it++){ 
out.println(cookies[i].getName() + ":" 
+ 


cookies[i].getValue() + "<br/>"); 
}//end for loop 
}//end if 


The output from Listing 8 is shown by the sessionID line and the lines for 
Tom and Dick in Figure 1. (The output from Listing 8 does not include the 
line for Harry.) The large numeric values to the left of Tom and Dick are 
the cookie names based on the number of milliseconds since January 1, 
1970. 


Display currently submitted field value 


Listing 9 displays the field value (Harry) submitted by the user for the 
current invocation of the servlet. This value is displayed at the end of the 
list as shown in Figure 1. Note that there is no cookie name associated with 
Harry in Figure 1. This value was not extracted from a named cookie for 
display. However, it will be displayed with a cookie name if the user calls 


the servlet again with a new field value before the cookie with the value 
Harry expires. 


Listing 9 - Display currently submitted field value. 


if(name != null){ 
out.printin(name + "<br/>"); 
}//end if 


The remaining code is typical of what you have seen in earlier modules. 
You can view that code in Listing 10 . 


The JSP program 


If you understand the explanation of the servlet code given above and you 
have understood the explanations of JSP code provided in earlier modules, 
you should have no difficulty understanding the JSP code provided in 
Listing 11. Therefore, I won't bore you with a detailed explanation of that 
code. The JSP code is provided simply for comparison with the servlet 
code. 


However, there is one point that is worth noting. If you compare Figure 2 
showing the JSP output with Figure 1 showing the servlet output, you will 
see that the JSP output contains an extra cookie named JSESSIONID . This 
is a unique session ID value that is automatically created by the JSP 
container. When writing servlets, you need to take the necessary steps to 
create a unique session ID. However, when writing JSP, that task is handled 
automatically for you so there is no need to create your own unique session 
ID. 


Run the programs 


I encourage you to copy the code from Listing 10 and Listing 11 . Install the 
programs on your server. Experiment with the code, making changes, and 
observing the results of your changes. Make certain that you can explain 
why your changes behave as they do. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e¢ Module name: Java4570: Session Tracking using Cookies 
e File: Java4570.htm 
¢ Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 


Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


Complete program listing 


Listing 10 - The servlet program named Java4570a.java. 


/*File Java4570a.java, Copyright 1999, R.G.Baldwin 
Rev 12/24/13 

The purpose of this program is to illustrate 
session 

tracking through the use of cookies. 


Each time the servlet is called, it displays an 
html 
form on the client screen. The form contains: 
An input field for submitting a name 
A submit button 
A list of previously submitted names 


The first time the servlet is called, it creates a 
unique session ID and stores it in a cookie on the 
browser. 


Each time the servlet is called, it creates a 
cookie 

containing the name submitted by the user and 
stores it 

on the browser. 


KEKEKKEKKEKKEKRKEKRKEKRKEKRKEKRKE KEKE KEKE KEKE KEKE KEKE KEKE KEKE KR KEKE KEKE KEKE KEKE KEKE REESE 
RRR, RR RT 

import java.io.*; 

import java.util.*; 

import javax.servlet.”*; 


import javax.servlet.http.*; 


public class Java4570a extends HttpServlet{ 
public void doGet(HttpServletRequest request, 
HttpServletResponse response) 
throws ServletException, 
IOException{ 


//Get a unique ID to be used to construct a 
session ID 

String uid = new 
java.rmi.server.UID().toString(); 

//Encode any special characters that may be in 
the uid 

// to construct the session ID 

String sessionID = 
java.net.URLEncoder.encode(uid); 


//Get and save the cookies submitted with the 
request 
Cookie[] cookies = request.getCookies(); 


//Get the submitted name for the current get 
request 

String name = 
request.getParameter("firstName") ; 


//Establish the type of output 
response.setContentType("text/html"); 


//Tf no cookies were submitted with the 
request, 
// create and add a cookie containing the 
session ID 
if(cookies == null){ 
Cookie newCookie = new 
Cookie("sessionID", sessionID); 


response. addCookie(newCookie) ; 
}//end if 


//Get an output stream 
Printwriter out = response.getwriter(); 


if(name != null){ 
String cookieName = "" + new 
Date().getTime(); 
Cookie newCookie = new Cookie(cookieName, 
name) ; 
newCookie.setMaxAge(60) ; 
response. addCookie(newCookie); 
}//end if 


//Construct an html form and send it back to 
the client 

out.printiln("<html>"); 

out .println("<head><title>Java4570a</title> 
</head>"); 

out.println("<body>"); 


//Substitute the name of your server in 

// the following statement. 

out.printin("<form method='get' action=" 

+ 

"'http://localhost:8080/Java4570a'>"); 

out.println("<p>Enter a name and press the 
button</p>"); 

out.println("<p>Name: <input type='text' 
name=" 

+ 

"'firstName'/></p>"); 

out.println("<input type='submit' value=" 

+ 

"'Submit Name'/>"); 

out.println( 


"<br/><br/>Your session ID and list of names 
is:<br/>"); 
if(name == null){ 
out.printin("Empty<br/>") ; 
}//end if 


//Display the session ID and the values of the 
// cookies that have been saved. 


if(cookies != null){ 
for(int 1 = 0; 1 < cookies.length; i++){ 
out.println(cookies[i].getName() + ":" + 


cookies[i].getValue() 
+ "ebr/>" 3 
}//end for loop 
}//end if 


//Display name submitted with current get 
request 
if(name != null){ 
out.println(name + "<br/>"); 
}//end if 
out.printiln("</form></body></htm1>" ) ; 


}//end doGet() 
}//end class Java4570a 


Listing 11 - The JSP program named Java4570b.jsp. 


<%@ page import='java.util.*,java.io.*' %> 
<html> 
<head><title>Java4570b</title></head> 
<body> 


<% 


String uid = new 
java.rmi.server.UID().toString(); 

String sessionID = 
java.net.URLEncoder.encode(uid) ; 


Cookie[] cookies = request.getCookies(); 
String name = 
request.getParameter("firstName") ; 


response.setContentType("text/html"); 


if(cookies == null){ 
Cookie newCookie = new 
Cookie("sessionID",sessionID); 
response.addCookie(newCookie); 
}//end if 


if(name != null){ 
String cookieName = "" + new 
Date().getTime(); 
Cookie newCookie = new Cookie(cookieName, 
name); 
newCookie.setMaxAge(60) ; 
response.addCookie(newCookie); 
}//end if 
%> 


<form method='get' 

action='http://localhost :8080/Java4570b.jsp'> 
<p>Enter a name and press the button</p> 
<p>Name: <input type='text' name='firstName'/> 

</p> 
<input type='submit' value='Submit Name'/> 


<br/><br/>Your session ID and list of names is: 
<br/> 


<% 
if(name == null){ 
out.printin("Empty<br/>"); 


}//end if 
if(cookies != null){ 
for(int i = 0; i < cookies.length; i++){ 
out.println(cookies[i].getName() + ":" + 
cookies[i].getValue() + 
"ebr/>" ); 
}//end for loop 
}//end if 


if(name != null){ 
out.println(name + "<br/>"); 
}//end if 
%> 
</form></body></html> 


-end- 


Java4570r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4570: Session Tracking using Cookies in the Servlets sub- 
collection. 


Table of Contents 


e Preface 
e Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INE W 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4570: Session Tracking using Cookies in the Servlets sub- 


collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


Cookies are information that is created by a web application and stored on 
the HTTP server. Under certain conditions, this information is retrieved and 
used by the HTTP server whenever a request is sent from the client to the 
server. 


Go to answer 1 


Question 2 
True or False? 


Cookies are widely used by various server-side programming techniques for 
session tracking. Java provides classes and methods designed to allow you 
to use cookies in your servlets. 


Go to answer 2 


Question 3 
True or False? 


Any HTTP server can obtain cookies from a browser regardless of the 
server that created the cookie. 


Go to answer 3 


Question 4 
True or False? 


By default, a cookie expires 24 hours after it is created. 


Go to answer 4 


Question 5 
True or False? 


The setMaxAge method can be called to override the default and specify 
the maximum age of a cookie in minutes. The cookie will expire when the 
maximum age has been reached. 


Go to answer 5 


Question 6 
True or False? 


The setMaxAge method can be called to override the default and specify 
the maximum age of a cookie in seconds. The parameter to the settMaxAge 
method is an int so the maximum age of a cookie can be years. 


Go to answer 6 


Question 7 
True or False? 


The setComment method can be used to provide a comment with the 
cookie. The browser may elect to make this information available to the 
user. 


Go to answer 7 


Question 8 
True or False? 


The constructor sets the name and value of a cookie when the Cookie 
object is instantiated. The setValue method can be used to assign a new 
value to the cookie after it is instantiated. 


Go to answer 8 


Question 9 
True or False? 


The JavaCookie class represents a cookie that can be used for session 
management with the HTTP protocol. 


Go to answer 9 


Question 10 
True or False? 


Each cookie has a name and a single value (a name::value pair) . It may 
have optional attributes, including: 


e A comment 

Path and domain qualifiers to specify which hosts can see the cookie 
e AA maximum age 

e A version. 


Go to answer 10 


Question 11 


True or False? 


Servers assign cookies, using fields added to HTTP response headers. In the 
Java API, cookies are saved one at a time into HTTP response headers, 
using the addCookie method. 


Go to answer 11 


Question 12 
True or False? 


Cookies are passed from the browser to the server using fields added to 
HTTP request headers. 


In the Java API, HTTP cookies are retrieved, one at a time, using the 
getCookies method. 


Go to answer 12 


Question 13 
True or False? 


Because cookies are sent to the browser using HTTP headers, they should 
be added to the response before you send any content. 


Go to answer 13 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None Cox) 


Display your namethiete. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


La} 
ab 
i 


4> 


pony 


Answers 


Answer 13 


True. 


Go back to Question 13 


Answer 12 
False. 


Cookies are passed from the browser to the server using fields added to 
HTTP request headers. 


In the Java API, HTTP cookies are retrieved using the getCookies method. 
This method returns all of the cookies found in the request sent by the 
client. 


Go back to Question 12 


Answer 11 
True. 


Go back to Question 11 


Answer 10 
True. 


Go back to Question 10 


Answer 9 


False. The Cookie class represents a cookie that can be used for session 
management with the HTTP protocol. 


Go back to Question 9 


Answer 8 
True. 


Go _ back to Question 8 


Answer 7 
True. 


Go back to Question 7 


Answer 6 
True. 


Go back to Question 6 


Answer 5 
False. The setMaxAge method can be called to override the default and 
specify the maximum age of a cookie in seconds. The cookie will expire 


when the maximum age has been reached. 


Go back to Question 5 


Answer 4 


False. By default, a cookie expires when the browser exits 


Go back to Question 4 


Answer 3 
False. 


By default, cookies are sent only to the host that caused them to be saved. 
Methods can be called to set attributes for each cookie that determine which 
servers will receive the cookie. For example, the setDomain method can be 
used to specify a domain pattern indicating which servers should receive a 
cookie. 


By default, cookies are sent to the page that set the cookie and to all the 
pages in that directory or under that directory. This also can be modified by 
calling the setPath method on the cookie. 


Go back to Question 3 


Answer 2 
True. 


Go back to Question 2 


Answer 1 


False. Cookies are information that is created by a web application and 
stored on the client machine by the browser. Under certain conditions, this 
information is sent to the HTTP server whenever a request is sent from the 
client to the server. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4570r-Review 
e File: Java4570r.htm 

e Published: 03/10/14 

e Revised: 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4580: Session Tracking using the Session Tracking API 
The purpose of this module is to explain session tracking using a servlet and 
the session tracking API. 


Table of Contents 
e Preface 
o Viewing tip 


=» Figures 
= Listings 


¢ General background information 
o Introduction 


o Program output 
o The HttpSession Interface 


e Discussion and sample code 
e Run the program 

e Miscellaneous 

¢ Complete program listing 


Preface 


This module is one in a collection of modules designed for teaching INE W 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
The purpose of this module is to explain session tracking using a servlet and 
the session tracking API . 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Output from access #1. 
e Figure 2. Output from access #2. 
e Figure 3. Output from access #3. 
e Figure 4. Output from access #4. 
e Figure 5. Output from access #5. 
e Figure 6. Output from access #6. 
e Figure 7. Output from access #7. 


Listings 


e Listing 1. Beginning of the doGet method. 

e Listing 2. Get the session object. 

e Listing 3.. Get an output stream. 

e Listing 4. A hit counter. 

e Listing 5. Insert a Date object into the session. 

e Listing 6. An object of type MyClass. 

e Listing 7. Display information about the session. 
e Listing 8. Display information about the objects. 
e Listing 9. The inner class named MyClass. 

e Listing 10. The servlet named Java4580a.java. 


General background information 


Introduction 


This is the fourth in a series of modules designed to show you how to 
implement session tracking using servlets. As mentioned earlier, the 
purpose of this module is to illustrate session tracking using the session 
tracking API . 


Earlier modules have illustrated three different ways to implement session 
tracking with servlets 


e hidden fields 


e URL rewriting 
e cookies 


A higher-level approach to session tracking 


The servlet programs in those earlier modules were written at a fairly low 
level. The session tracking API allows you to program at a somewhat 
higher level. Before you get too excited, however, be aware that this may or 
may not be the answer to your needs. In some cases, depending on the 
server involved, you may find that the session tracking API relies 
exclusively on cookies. If that is the case with your server and if your 
clients don't allow cookies, then the API may not meet your needs. You 
may find yourself back at square one -- hidden fields or URL rewriting . 


The HttpSession interface 


The capability that I have referred to as the session tracking API is 
primarily based on the HttpSession interface that I will discuss later. It also 
includes some other interfaces and classes as well. 


Program output 


Figure 1 through Figure 7 show the output produced by the servlet named 
Java4580a for each of the first seven times it is accessed by the same 
browser. You might just want to glance over these Figures now. I will refer 
back to them and explain their meaning throughout the discussion of the 
servlet. 


Figure 1 - Output from access #1. 


Java4530a 


€ — C ff 6 localhost:8080/Java4580a 


Event 
In valueBound method 
Name = MyClassObj 


Session Characteristics: 

New Session: true 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:05:05 CST 2013 


Session Data: 

counter: 1 

1388462705670: Mon Dec 30 22:05:05 CST 2013 

out: org.apache.catalina.connector.Coyote Writer@ 1d0bc9e9 
MyClassObj: This is a MyClass object 


Figure 2 - Output from access #2. 


[a] Java45s0a 
€ — C ff BG localhost:8080/Java4580a 


Session Characteristics: 

New Session: false 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:05:05 CST 2013 


Session Data: 

counter: 2 

1388462705670: Mon Dec 30 22:05:05 CST 2013 

out: org.apache.catalina.connector.Coyote Writer@ 1d0bc9e9 
1388462784494: Mon Dec 30 22:06:24 CST 2013 
MyClassObj: This is a MyClass object 


Figure 3 - Output from access #3. 


Java4530a 


€ — C ff 6 localhost:8080/Java4580a 


Session Characteristics: 

New Session: false 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:06:24 CST 2013 


Session Data: 

counter: 3 

1388462705670: Mon Dec 30 22:05:05 CST 2013 

out: org.apache.catalina.connector. Coyote Writer@ 1d0bc9e9 
1388462784494: Mon Dec 30 22:06:24 CST 2013 
MyClassObj: This is a MyClass object 

1388462831954: Mon Dec 30 22:07:11 CST 2013 


Figure 4 - Output from access #4. 


Java4530a 


€ — C ff [5 localhost:8080/Java4580a 


Event 
In valueUnbound method 
Name = MyClassObj 


Session Characteristics: 

New Session: false 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:07:11 CST 2013 


Session Data: 

counter: 4 

1388462876283: Mon Dec 30 22:07:56 CST 2013 
1388462705670: Mon Dec 30 22:05:05 CST 2013 

out: org.apache.catalina.connector.Coyote Writer@ 1d0bc9e9 
1388462784494: Mon Dec 30 22:06:24 CST 2013 
1388462831954: Mon Dec 30 22:07:11 CST 2013 


Figure 5 - Output from access #5. 


Java4530a 


€ — C ff 5 localhost:8080/Java4580a 


Session Characteristics: 

New Session: false 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:07:56 CST 2013 


Session Data: 

counter: 5 

1388462876283: Mon Dec 30 22:07:56 CST 2013 
1388462921409: Mon Dec 30 22:08:41 CST 2013 
1388462705670: Mon Dec 30 22:05:05 CST 2013 

out: org.apache.catalina.connector.Coyote Writer@ 1d0bc9e9 
1388462784494: Mon Dec 30 22:06:24 CST 2013 
1388462831954: Mon Dec 30 22:07:11 CST 2013 


Figure 6 - Output from access #6. 


[a] Java45s0a 
€ — C ff BG localhost:8080/Java4580a 


Session Characteristics: 

New Session: false 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:08:41 CST 2013 


Session Data: 

counter: 6 

1388462876283: Mon Dec 30 22:07:56 CST 2013 
1388462921409: Mon Dec 30 22:08:41 CST 2013 
1388462705670: Mon Dec 30 22:05:05 CST 2013 
1388462972243: Mon Dec 30 22:09:32 CST 2013 

out: org.apache.catalina.connector.Coyote Writer @ 1d0bc9e9 
1388462784494: Mon Dec 30 22:06:24 CST 2013 
1388462831954: Mon Dec 30 22:07:11 CST 2013 


Figure 7 - Output from access #7. 


[a] Java45s0a 
€ — C AF 1 localhost:8080/Java4580a 


Session Characteristics: 

New Session: false 

Session ID: 815FDAF004D201D2EA672A0E9BEE468E 

Session Context: org.apache.catalina session. StandardSessionContext@4cb2018c 
Creation Time: Mon Dec 30 22:05:05 CST 2013 

Last Accessed: Mon Dec 30 22:09:32 CST 2013 


Session Data: 

counter: 7 

1388462876283: Mon Dec 30 22:07:56 CST 2013 
1388462921409: Mon Dec 30 22:08:41 CST 2013 
1388462705670: Mon Dec 30 22:05:05 CST 2013 
1388462972243: Mon Dec 30 22:09:32 CST 2013 

out: org.apache.catalina.connector.Coyote Writer@ 1d0bc9e9 
1388462784494: Mon Dec 30 22:06:24 CST 2013 
1388462831954: Mon Dec 30 22:07:11 CST 2013 
1388463023739: Mon Dec 30 22:10:23 CST 2013 


The HttpSession Interface 


I will explain the code in this servlet in fragments. A complete listing of the 
servlet is provided in Listing 10 . 


Beginning of the doGet method 


Listing 1 shows typical code for beginning the definition of a servlet class 
and for beginning the definition of the doGet method. You have seen code 
like this in earlier modules so I won't discuss it further in this module. 


Listing 1 - Beginning of the doGet method. 


import java.io.*; 

import java.util.*; 

import javax.servlet.”*; 
import javax.servlet.http.*; 


public class Java4580a extends HttpServlet{ 


public void doGet(HttpServletRequest 
request, 
HttpServletResponse 
response) 
throws 
ServletException, IOException{ 


Get the session object 


I will continue the discussion with the code fragment shown in Listing 2 , 
where request is a reference to the standard object of type 
HttpServletRequest passed to the doGet method that begins in Listing 1. 


Listing 2 - Get the session object. 


HttpSession session = 
request.getSession(true); 


An object of type HttpSession 


The call to the getSession method in Listing 2 returns a reference to an 
object of the interface type HttpSession . As you can see, the reference is 
saved in the local variable named session . 


The HttpSession object provides an association (a session) between an 
HTTP client and an HTTP server. This association, or session, persists over 
multiple connections and/or requests during a given time period. Sessions 
are used to maintain state and user identity across multiple page requests. 


How is the session maintained? 


Apparently the manner in which the association between the client and the 
server (the session) is maintained varies from one server to the next. One 
books states, 


"A session can be maintained either by using cookies or by URL 
rewriting." 


Another book states that the minimum requirement for servers is to 
maintain the session using cookies, and that the server may optionally 
support URL rewriting as well. There are inferences in other books to the 
effect that some servers may not support URL rewriting. 


The HttpSession object 


The HttpSession object returned by the code in Listing 2 behaves as a 
container for the storage of: 


e Information about the session 
e Data (objects) that persist from one call to the servlet to the next call to 
the servlet by the same client. 


Client ID is transparent 


The requirement to maintain the identification of each individual client is 
transparent to the programmer. That information is encapsulated in the 


HttpSession object and the process that backs it up. 
The lifetime of a session 


An HttpSession object represents an ongoing session with a particular 
client. The actual lifetime of a session isn't clear in the books that I have 
read. 


The books seems to imply that the session can remain active over long 
periods of time. However, on my local Tomcat server, the session ends 
when the browser is terminated. The behavior is similar to that which 
occurs with the default behavior of cookies that expire when the browser 
exits. 


(Recall however, the setMaxAge method can be called on a 
cookie to cause it to persist beyond the current active period of 
the browser. Browsers save long-life cookies from one active 
period to the next. There may be some way to accomplish that 
using the session tracking API as well but that is speculation on 


my part.) 


On my server, the session continues until 


e The client exits the browser 
e The servlet purposely invalidates the session 
e The server invalidates the session due to timeout or other condition 


Maintaining session state 


All that the programmer has to do to maintain session state is to put objects 
into the HttpSession object, and to get objects from the HttpSession 
object. 


The programmer can also get information about the session from the 
HttpSession object as well. 


Name::value pairs 


Data objects are stored in the HttpSession object using a dictionary-like 
interface. Each object stored in the HttpSession object is stored under a 
String name. Data objects are retrieved under the name associated with the 
object. (This is another case of using name: :value pairs.) 


The fact that the data objects may actually be stored on the client machine 
(possibly in cookies) is transparent to the programmer. 


Is the data stored in cookies? 


With my local Tomcat server, the fact that the data objects are being stored 
in cookies on the client machine can be verified by setting the browser 
preferences to disallow the use of cookies. This results in the counter value 
that I will explain later never progressing beyond that shown in Figure 1 . 
This indicates that the servlet is unable to establish a session when cookies 
are disabled. 


Events 


If you instantiate your data objects from classes of your own design, you 
can process events that are generated whenever the object is put in or 
removed from the HttpSession object. In order to be able to receive events, 
your classes must implement the HttpSessionBindingListener interface. 


(I also believe, but am not certain, that in order for the objects 
instantiated from your classes to be eligible for being saved in the 
session object, your classes must implement the Serializable 
interface. This makes it possible to decompose an object into a 
stream of bytes and to reconstruct those bytes into an object 
later.) 


Event handlers 


When a data object of a class that implements the 
HttpSessionBindingListener interface is put into the HttpSession object, 
the following method is called on the data object: 


value Bound(HttpSessionBindingEvent e) 


When a data object of a class that implements the 
HttpSessionBindingListener interface is removed from the HttpSession 
object, the following method is called on the data object: 


value Unbound(HttpSessionBinding Event e) 
No registration is required 


Unlike the typical case in Java programming, no special registration of the 
event listener is required. Simply implementing the interface on the object 
is sufficient to cause it to receive events when it is put into or removed from 
the HttpSession object. You can define those two methods to provide 
whatever behavior may be needed when the events occur. 


The isNew method 


An implementation of HttpSession represents the server's view of the 
session. The server considers a session to be new until the client has joined 
it. Until the client joins the session, the isNew method returns true. 


A value of true can indicate one of the following three cases: 


e The client does not yet know about the session 
e The session has not yet begun 
e The client chooses not to join the session. 


The third case will occur if the server supports only cookies and the client 
chooses to reject cookies sent by the server (the client has disabled cookies 
on the browser) . 


URL rewriting 


According to the some books, the third case will not commonly occur, if the 
server supports URL rewriting. However, according to one of my books, 
even if the server supports URL rewriting, that capability is not freely 
available. The programmer must provide special programming constructs to 
take advantage of URL rewriting. 


In any event, it is the responsibility of the programmer to design the 
application to account for situations where a client has not joined a session. 


Discussion and sample code 


Now that you have the background information under your belt, let's take a 
look at a sample program. 


The name of the servlet that I will explain in this module is Java4580a . As 
mentioned earlier, I will explain this program in fragments. A complete 
listing is provided in Listing 10 . 


Beginning of the servlet program 
The program begins in the typical manner shown earlier in Listing 1. Then 


the program gets a valid HttpSession object for the current request from the 
client as shown by the call to the getSession method in Listing 2 . 


What does Oracle have to say? 


Here is some of what Oracle has to say about the getSession method, where 
create is the name of the boolean parameter passed to the method: 


"Returns the current HttpSession associated with this request or, 
if there is no current session and create is true, returns a new 
session. If create is false and the request has no valid 
HttpSession , this method returns null. To make sure the session 
is properly maintained, you must call this method before the 
response is committed." 


Apparently the server identifies the first request of the session by the fact 
that the browser doesn't send a cookie (or the URL hasn't been rewritten) , 
but that is just speculation on my part. 


Get an output stream 


An output stream is needed in order for the servlet to send content to the 
client browser. An output stream object is created and saved in the session 
object, thus making it available for as long as the session is active. 


You are already familiar with the first statement in Listing 3 , so nothing 
more needs to be said about that statement. 


Retrieve the stream object from the session object 


Beyond that, the code in Listing 3 begins by attempting to retrieve an 
output stream object from the session object. 


If the call to the getValue method on the session object returns null, this 
indicates that an output stream has not yet been created and saved in the 
session object. In that case, an output stream object is created and put into 
the session object where it will be available on subsequent requests to the 
servlet. 


A reference to the new output stream is also saved in the local variable 
named out so that it will be available during the remainder of the doGet 
method. This is what happens at the beginning of a new session with a 
specific browser. 


Listing 3 - Get an output stream. 


Listing 3 - Get an output stream. 


response.setContentType("text/html"); 


Printwriter out = 
(Printwriter )session.getValue("out"); 
if(out == null){ 
//First request from this client 
out = response.getwriter(); 
session.putValue("out", out); 
}//end if 


//Create HTML page header 
out.println("<html>"); 
out.println( "<head> 
<title>Java4580a</title></head>") ; 
out.println("<body>"); 


An output stream already exists 


If the call to the get Value method in Listing 3 returns an output stream, a 
reference to the output stream is saved in the local variable named out . 
This is what happens in the second and subsequent calls to the servlet 
during an ongoing session with a specific browser. 


Create the HTML header text 


Once the output stream is available, the code in Listing 3 uses it to create 
the normal header text on the outgoing HTML page. 


A hit counter 


Listing 4 instantiates a hit counter object and stores it in the session object 
under the name " counter ". If the session doesn't have a counter , one is 
created and its value is initialized to 1. If the session already has a counter , 


it is incremented by 1. Then the new or incremented counter is put in the 
session, replacing the one that was already there. 


Listing 4 - A hit counter. 


Integer cnt = 
(Integer )session.getValue("counter"); 


if(cnt == null) cnt = new Integer(1); 

else cnt = new Integer(cnt.intValue() + 
1); 

session.putValue("counter",cnt); 


Note that because an object of the Integer class is immutable, the only way 
to increment the counter is to create a new Integer object to replace the 
existing one. 


The putValue and getValue methods 


Listing 4 also illustrates the putValue and getValue methods. These 
methods are used to store and retrieve objects from the session object. The 
putValue() method requires two parameters: 


e an object to be stored 
e the String name under which the object is to be stored 


The getValue method requires the String name of the object to retrieve. 


Insert a Date object into the session 


As shown in Listing 5, each time the servlet is called, a new Date object 
containing the current date and time is instantiated and stored in the session 
object. 


Listing 5 - Insert a Date object into the session. 


Date theDate = new Date(); 

long millis = theDate.getTime(); 
String strMillis = "" + millis; 
session.putValue(strMillis, theDate) ; 


Each Date object is stored under a name created by converting the current 
date and time in milliseconds to a String . Thus, the amount of data stored 
in the session object increases with each call to the servlet. 


(Note that if the servlet is called twice by the same client within 
one millisecond, this naming scheme will fail due to duplicate 
names being created and put into the session object.) 


An object of type MyClass 


When the value of the hit counter is 1, an object of type MyClass is 
instantiated and stored in the session object under the name MyClassObj . 
This is shown in Listing 6. Note in particular that a reference to the output 
stream object is passed to the constructor for the MyClass object. You will 
see why later. 


Listing 6 - An object of type MyClass. 


if(cnt.intValue() == 1) 
session.putValue("MyClassObj", 
new MyClass(out)); 
if(cnt.intValue() == 4) 
session.removeValue("MyClassObj"); 


Also as shown in Listing 6, this object is removed from the session object 
when the value of the hit counter is 4. 


An HttpSessionBindingEvent event happens when the object is put into 
the session object and happens again when the object is removed from the 
session object. 


Event handling 


The object of type MyClass is a listener for events of type 
HttpSessionBindingEvent . Therefore, it receives an event notification 
when it is put into the session object, and receives another event notification 
when it is removed from the session object. Information about the two 
events is displayed on the client screen when the events occur. 


The text at the top of Figure 1 was produced when the MyClass object was 
put into the session. The text at the top of Figure 4 was produced when the 
object was removed from the session. More information about that text will 
be provided later during the discussion of the class named MyClass . 


Display information about the session 


The code in Listing 7 displays several pieces of information about the 
session each time the servlet is called. This information is obtained from the 
session object by calling various methods on the session object. The 


information is then mixed with standard HTML code and displayed on the 
client screen as shown in Figure 1 through Figure 7 . 


Listing 7 - Display information about the session. 


out.println("<p>Session Characteristics: 
<br/>"); 

out.println("New Session: " + 
session.isNew()+ "<br/>"); 

out.println("Session ID: " + 
session.getid()+ "<br/>"); 

out.println("Session Context: " 

+ 

session.getSessionContext()+ "<br/>"); 

out.println("Creation Time: " 

+ new 

Date(session.getCreationTime()) + "<br/>"); 

out.printin("Last Accessed: " 

+ new 

Date(session.getLastAccessedTime()) + "</p>"); 


Display information about the objects 


The code in Listing 8 displays information about each of the objects stored 
in the session object each time the servlet is called. Note that the order of 
the display of objects doesn't seem to follow any particular pattern. 


Listing 8 - Display information about the objects. 


out.println("<p>Session Data:<br/>"); 
String[] names = session.getValueNames(); 
for(int 1 = 0; 1 < names.length; it++){ 
out.println(names[i] + ": " 
+ 
session.getValue(names[i]) + "<br/>"); 
}//end for loop 


//Finish off the HTML page 
out.println("</p></body></htm1>"); 
}//end doGet() 


The code in Listing 8 calls the getValueNames method to create a String 
array containing the names of each of the objects currently stored in the 
session object. A for loop then iterates on that array, calling the getValue 
method on each name to get and display each of the objects stored in the 
session object. 


(The code in Listing 8 also finishes off the web page and signals 
the end of the doGet method.) 


The information that is displayed 


The following information about the objects is displayed in Figure 1 
through Figure 3 : 


e counter information 
e information about each of the Date objects 
e information about the output stream object 


e information about the object of type MyClass . 


Beginning with Figure 4, the MyClass object is no longer contained in the 
session object when the list is constructed, so only information about the 
first three items in the above list is displayed. 


Miscellaneous things worthy of note 
In Figure 1, you see three types of information being displayed: 


e Event 
e Session Characteristics 
e Session Data 


The Event output resulted from the fact that the object of type MyClass 
was put into the session object. This caused the valueBound method to be 
called. 


The Session Characteristics show that the creation time and the time last 
accessed are equal, and the session is a new session. 


The Session Characteristics also show the Session ID which has been 
automatically created for this session and the Session Context , which is 
peculiar to the Tomcat server being used. Neither of these will change for 
the duration of the session. 


The Session Data in Figure 1 shows information on one counter object, one 
Date object, one output stream object, and one object of type MyClass . 


Figure 1 through Figure 7 all show the same Session ID and the same 
Session Context . 


(Note that unlike the servlet code in earlier modules, I did not 
write the code that created the session ID.) 


In Figure 2 and Figure 3 , you see only two types of information being 
displayed: 


e Session Characteristics 
e Session Data 


There is no event output in these two Figures because the object of type 
MyClass is neither put into nor removed from the session during these calls 
to the servlet. 


Beginning with Figure 2 , the New Session value shows false. In other 
words, the session is no longer new. 


Beginning with Figure 3, the Last Accessed time differs from the 
Creation Time . 


The entire sequence of Figures show a sequence of seven calls to the 
servlet. Hence, the value of the counter increases by one in each succeeding 
Figure. Also, the number of objects in the list increases by one during each 
of the first three Figures. 


Figure 4 shows the screen output for the fourth call to the servlet. This is 
the call where the MyClass object was removed from the session object. 
Hence an Event occurred showing that the valueUnbound method was 
called. 


The Session Data consists of one counter object, one output stream object, 
and four Date objects. The MyClass object no longer appears in the list 
because it was removed from the session object before the list was 
constructed. 


Finally, Figure 7 shows the screen output for the seventh call to the servlet. 
There is no Event output and the Session Characteristics are the same as 
before except for the time last accessed. 


The Session Data consists of one counter object, one output stream object, 
and seven Date objects. 


The inner class named MyClass 


The code in Listing 9 defines an inner class named MyClass . It could have 
been implemented as a top-level class but I elected to make it an inner class 


(actually a member class ) . 


Listing 9 - The inner class named MyClass. 


Class MyClass implements 
HttpSessionBindingListener, 


Serializable{ 
Printwriter localOut;//local copy of 
output stream to client 


public MyClass(PrintWriter out) 
{//constructor 
//Save a local copy of the output stream 
to the client. 
localOut = out; 
}//end constructor 


public String toString(){ 
return "This is a MyClass object"; 
}//end toString() 


//This method is called when the object is 
put into 
// the session. 
public void 
valueBound(HttpSessionBindingEvent e){ 
localOut.printin("<p>Event<br/>") ; 


Listing 9 - The inner class named MyClass. 


localOut.printin("In valueBound 
method<br/>"); 

//Returns the name of the object as 
identified when 

// put into the session 

localOut.printin("Name = " +e.getName( ) 
+ "</p>"); 

}//end valueBound( ) 


//This method is called when the object is 
removed 
// from the session. 
public void 
valueUnbound(HttpSessionBindingEvent e){ 
localOut.printin("<p>Event<br/>"); 
localOut.printin("In valueUnbound 
method<br/>"); 
localOut.printin("Name = " +e.getName( ) 
+ "</p>"); 
}//end valueUnbound( ) 
}//end inner class named MyClass 


}//end class Java4580a 


Deploying the servlet 
When this program is compiled, it produces the following two class files: 


e Java4580a.class 
e Java4580a$MyClass.class 


The second class file results from the compilation of the member class. 


I mention this as a reminder that it is necessary to copy both of these class 
files in order to deploy the servlet onto a web server. Note however that 
when deploying on my local Tomcat server, only the information about the 
top level class must be entered into the file named web.xml . 


A MyClass object 


An object of the class named MyClass is instantiated and put into the 
session object during the first call to the servlet when the hit counter equals 
one. (See Listing 6.) The object is removed during the fourth call to the 
servlet when the hit counter equals four. (Again, see Listing_6 .) 


A listener object 


Because the class implements the HttpSessionBindingListener interface, 
an object of the class is a listener for events of type 
HttpSessionBindingEvent . An event of this type occurs when the object is 
put into the session object. Another event of this type occurs when the 
object is removed from the session object. 


Event handler methods 


The method named valueBound is called when the object is put into the 
session object. The method named valueUnbound is called when the object 
is removed from the session object. 


No registration necessary 


Unlike typical Java event programming, it is not necessary to register the 
listener on a source. Simply implementing the 
HttpSessionBindingListener interface is sufficient to cause the object to 
be notified of the events when an object of the class is put into or removed 
from the session object. 


An object of type HttpSessionBindingEvent 


When an event occurs, the event handler methods named valueBound and 
valueUnbound receive a reference to an object of type 


HttpSessionBindingEvent as a parameter. 


In this program, the event handlers call the getName method on the event 
objects to display information about the events on the client screen when 
the events occur. This is shown in Figure 1 and Figure 4. Several other 
methods are available to be called on the event object including: 


e getName 
e getSession 
e getValue 
e getSource 


An overridden toString method 


In addition to the two event handler methods, the MyClass class also 
overrides the toString method. Note that the string returned by the 
overridden toString method is displayed in Figure 1 through Figure 3 to 
represent the MyClass object that is contained in the session object. 


Event handler behavior 


My objective was to display the name returned by the getName method on 
the browser screen for each event as shown by the third line in Figure 1 and 
the third line in Figure 4 . In order to accomplish this, the code in the event 
handler methods need access to the output stream object. This was 
accomplished by 


e passing a reference to the output stream object to the MyClass 
constructor 

e saving that reference in an instance variable of the MyClass object 

e using that reference inside the event handler methods to send content 
to the browser 


Standard source-listener event handling 


Except for the fact that there is no requirement to register the event listener 
object on a source, this is straightforward source-listener event handling 
material that you should already be familiar with. 


The code in Listing 9 also signals the end of the class named Java4590a . 


Run the program 


I encourage you to copy the code from Listing 10. Compile the code and 
deploy it on your server. Experiment with the code, making changes, and 
observing the results of your changes. Make certain that you can explain 

why your changes behave as they do. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4580: Session Tracking using the Session 
Tracking API 

e File: Java4580.htm 

e Published: 12/30/13 

¢ Revised: 02/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 


nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


Complete program listing 


Listing 10 - The servlet named Java4580a.java. 


/*File Java4580a.java, Copyright 1999, R.G.Baldwin 
Revised 12/30/13 


This servlet illustrates use of the session 
tracking API. 

A variety of different aspects of session tracking 
using 

the API are illustrated. 


KREKEKKEKKEKRKEKRKEKRKEKRKEKRKEKRKE KEKE KEK KEKE KEKE KEKE KEKE KR KEK KEK KEKE KEKE KEKE 
FR CR ew 

import java.io.*; 

import java.util.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 


public class Java4580a extends HttpServlet{ 
public void doGet(HttpServletRequest request, 
HttpServletResponse response) 
throws 
ServletException, IOException{ 


//Get the session associated with this 


request, 
HttpSession session = 
request.getSession(true); 


response.setContentType("text/html"); 


//Get the output stream from the session 
object. 
// If this is the first call to servlet, 
create an output 
// stream and save it in the session object. 
Printwriter out = 
(PrintWriter )session.getValue("out"); 
if(out == null){ 
//First request from this client 
out = response.getwriter(); 
session.putValue("out", out); 
}//end if 


//Create HTML page header 

out.println("<html>"); 

out .println("<head><title>Java4580a</title> 
</head>") ; 

out.println("<body>"); 


//Create a hit counter for this servlet 
Integer cnt = 

(Integer )session.getValue("counter"); 
if(cnt == null) cnt = new Integer(1); 
else cnt = new Integer(cnt.intValue() + 1); 
session.putValue("counter",cnt); 


//Add a new Date object each time the servlet 
i called 

Date theDate = new Date(); 

long millis = theDate.getTime(); 

String strMillis = "" + millis; 


session.putValue(strMillis, theDate); 


//When the hit counter is 1, instantiate a new 
object of 

// type MyClass and put it in the session. 
Pass 

// a reference to the output stream to the 
constructor. 

//Remove the object from the session when the 
value 

// of the hit counter is 4. 

if(cnt.intValue() == 1) 

session.putValue("MyClassObj", new 

MyClass(out)); 

if(cnt.intValue() == 4) 
session.removeValue("MyClassObj"); 


//Display information about the session. 

out.println("<p>Session Characteristics: 
<br/>"); 

out.println("New Session: " + session.isNew( )+ 
"<br/>"); 

out.println("Session ID: " + session.getId()+ 
Nepr/>" ); 

out.println("Session Context: " 

+ 

session.getSessionContext()+ "<br/>"); 

out.printlin("Creation Time: " 

+ new 

Date(session.getCreationTime()) + "<br/>"); 

out.println("Last Accessed: " 

+ new 

Date(session.getLastAccessedTime()) + "</p>"); 


//Display information about all of the objects 
Currently in 
// the session. Note that the session now 


contains a 

// PrintWriter object that was not in the 
session in the 

// original version of the servlet named 
Java4580a. 

out.println("<p>Session Data:<br/>"); 

String[] names = session.getValueNames(); 

for(int 1 = 0; i < names.length; i++){ 

out.println(names[i] + ": " 
+ 

session.getValue(names[i]) + "<br/>"); 

}//end for loop 


//Finish off the HTML page 
out.println("</p></body></html1>"); 
}//end doGet() 


//This 1S an inner class. In the original 
version, this 

Class MyClass implements 
HttpSessionBindingListener, 


Serializable{ 
Printwriter localOut;//local copy of output 
stream to client 


public MyClass(PrintWriter out){//constructor 
//Save a local copy of the output stream to 
the client. 
localOut = out; 
}//end constructor 


public String toString(){ 
return "This is a MyClass object"; 


}//end toString() 


//This method is called when the object is put 
into 
// the session. 
public void valueBound(HttpSessionBindingEvent 
e)t{ 
localOut.printiln("<p>Event<br/>"); 
localOut.printin("In valueBound 
method<br/>") ; 
//Returns the name of the object as 
identified when 
// put into the session 
localOut.printin("Name = " +e.getName() + " 
</p>"); 
}/7end valueBound( ) 


//This method is called when the object is 
removed 
// from the session. 
public void 
valueUnbound(HttpSessionBindingEvent e){ 
localOut.printin("<p>Event<br/>"); 
localOut.printin("In valueUnbound 
method<br/>"); 
localOut.printin("Name = " +e.getName() + " 
</p>"); 
}//end valueUnbound( ) 
}//end inner class named MyClass 


}//end class Java4580a 


-end- 


Java4580r-Review 

This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 
This module contains review questions and answers keyed to the module 
titled Java4580: Session Tracking using the Session Tracking API in the 
Servlets sub-collection. 


Table of Contents 


e Preface 
e Questions 


e Answers 
e Miscellaneous 


Preface 


This module is one in a collection of modules designed for teaching INEW 
2338 Advanced Java (Web) at Austin Community College in Austin, TX. 


This module contains review questions and answers keyed to the module 
titled Java4580: Session Tracking using the Session Tracking API in the 
Servlets sub-collection. 


Once you study that module, you should be able to answer the review 
questions in this module. 


The questions and the answers in this module are connected by hyperlinks 
to make it easy for you to navigate from the question to the answer and 
back again. 


Questions 


Question 1 


True or False? 


The session tracking API allows you to program at a somewhat higher level 
than when programming for 


e hidden fields 
e URL rewriting 
e cookies 


Go to answer 1 


Question 2 
True or False? 


In some cases, depending on the server involved, the session tracking API 
may rely exclusively on cookies "under the hood." 


Go to answer 2 


Question 3 
True or False? 


The session tracking API is primarily based on the JavaHttpSession 
interface. It also includes some other interfaces and classes as well. 


Go to answer 3 


Question 4 


True or False? 


A call to the getSession method of the incoming request object returns a 
reference to an object of the interface type HttpSession . 


The HttpSession object provides an association (a session) between an 
HTTP client and an HTTP server. This association, or session, persists over 
multiple connections and/or requests during a given time period. Sessions 
can be used to maintain state and user identity across multiple page 
requests. 


Go to answer 4 
What is the meaning of the following two images? 
These images were inserted here simply to insert some space between the 


questions and the answers to keep them from being visible on the screen at 
the same time. 


None ee 
Display your nametheke 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 4 
True. 


Go back to Question 4 


Answer 3 


False. The session tracking API is primarily based on the HttpSession 
interface. It also includes some other interfaces and classes as well. 


Go back to Question 3 


Answer 2 


True. 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Java4580r-Review 
e File: Java4580r.htm 

Published: 03/10/14 

e Revised: 12/26/14 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 


book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0195: Preface to JSON 
This is the preface page for a section on the json-simple Java library. 


Revised: Thu Jun 02 18:43:34 CDT 2016 
This page is included in the following Books: 


e INEW2338 - Advanced Java Programming 
¢ Object-Oriented Programming_(QOP) with Java 


Table of contents 


e Table of contents 
e Servlets, search engines, or JSON 
e Miscellaneous 


Servlets, search engines, or JSON 


As explained in the page titled Java4510: Preface to INEW 2338 , only one 
of the topics Search Engines , Servlets , or JSON is covered in the course in 
any particular semester. However, all three are important. The course 
material in the Blackboard course management program indicates which 
topic is covered in the current semester. 


Students are encouraged to study all three topics for their own educational 
purposes in order to enhance their prospects of landing a job as a Java 
programmer. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0195: Preface to JSON 


e File: Json0195.htm 
e Published: 06/02/16 


Short summary: 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0200: The What and Why of JSON 
Learn what JSON is and why, as a Java programmer, you should care about 
JSON. 


Revised: Sun Jul 03 10:16:32 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library.. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


e Table of contents 
e Preface 


What is JSON? 

Why should you care about JSON? 
Not a book about JSON 

Viewing tip 


o Oo 0 90 


e Background information 


o A lightweight text-based data interchange format 
o Typical operation 
o A real-world analogy 


= No longer an object 
= Reassemble the parts 
= Streamlined procedures 


e Online references 
e Miscellaneous 


Preface 


What is JSON? 


The online document titled Introducing JSON begins as follows: 


Note: 

"JSON (JavaScript Object Notation) is a lightweight data-interchange 
format. It is easy for humans to read and write. It is easy for machines to 
parse and generate. It is based on a subset of the JavaScript Programming 
Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a 
text format that is completely language independent but uses conventions 
that are familiar to programmers of the C-family of languages, including C, 
C++, C#, Java, JavaScript, Perl, Python, and many others. These properties 
make JSON an ideal data-interchange language." 


Similarly, the online document titled Java API for JSON Processing: An 
Introduction to JSON begins as follows: 


Note: 

JSON (JavaScript Object Notation) is a lightweight, text-based, language- 
independent data exchange format that is easy for humans and machines to 
read and write. JSON can represent two structured types: objects and 
arrays. An object is an unordered collection of zero or more name/Vvalue 
pairs. An array is an ordered sequence of zero or more values. The values 
can be strings, numbers, booleans, null, and these two structured types. 


It is important to note that even though JSON is based on JavaScript syntax, 
JASON is not JavaScript nor is it any other programming language. In fact, 
it is not a programming language at all. As stated above, JSON is simply "a 
lightweight, text-based, language-independent data exchange format" -- 
nothing more and nothing less. 


Figure 1 shows a JSON text string containing name/value pairs as well as 
nested arrays. 


Note: Figure 1. Example JSON text. 


{ 
"game": 
GEO! ¢ 
"2-club","3-heart","4-diamond", '"5-spade" 
1, 
"name":"Tom" 
ty 
{"cards": 
"4-heart", "5-heart", "6-club", '"7-diamond" 
1, 
"name": "Joe" 
h 
] 
i; 


(This JSON text will be used in a Java program in a future module.) 


Why should you care about JSON? 


This book is being written and published under the following assumptions: 


e You are interested in Java programming. 
e You are interested in web development involving Java programming. 


e At some point in the future, you may become interested in Big Data . 
e At some point in the future, you may become interested in NoSQL 
databases such as MongoDB and Couchbase . 


As stated in the InfoWorld article of August 25, 2014: 


Note: 

"Web developers love JSON (JavaScript Object Notation). Like XML, it's 
a human-readable format for transmitting data, except it's a whole lot easier 
to work with than XML. ... Several NoSQL databases -- including the 
wildly successful MongoDB and Couchbase -- store data in JSON 
documents natively." 


According to How JSON and Big Data Will Shape the Internet of Things , 
the author writes: 


Note: 

"To answer the question of why JSON would be the most widely used 
format for the Internet of Things, one only need look at the rapid 
development of Raspberry Pi, which started a little over two-and-a-half 
years ago, and has gained massive traction worldwide. This credit-card 
sized microcomputer is extensible, and a recent project called RaZberry 
has turned it into a device capable of controlling your home automation 
through - you guessed it - a JSON interface. With future development of 
the Internet of Things, the proliferation of JSON as the preferred data 
delivery mechanism will only increase. 

Even more interesting is how this data can be fed into a Big Data cluster to 
perform predictive modeling and analytics. Just over a year ago, Google 
BigQuery_added support for JSON and explicitly mentions how sensor data 
and its attributes can be measured as a consequence. With time, it is only 
inevitable that developers in other Big Data ecosystems will use JSON 


when setting up their clusters to perform analytics from the various source 
data from the Internet of Things." 


article: 


Note: 

"JSON is the data format of the web. JSON is used to power most modern 
websites, is a native format for many NoSQL databases hosting top web 
applications, and provides the primary data format in many REST APIs. 
Google BigQuery, our cloud service for ad-hoc analytics on big data, has 
now added support for JSON and the nested/repeated structure inherent in 
the data format." 


I could go on providing similar quotations, but the bottom line is that if you 
anticipate your Java programming career taking you into the world of Big 
Data or into The Internet of Things at some point in the future, you 
probably need to learn how to write Java programs that parse, generate, 
transform, and query JSON. 


Not a book about JSON 


This book is not intended to teach you about JSON. There are numerous 
tutorials on the web that you can access for that purpose (see Online 
references ) . This book is intended to teach you how to use the json-simple 
Java library, (which is one of several available libraries), to parse, generate, 
transform, and query JSON. 


The page at http://www.json.org/ lists more than two dozen Java libraries 
that have been created for processing JSON data. After conducting an 
informal review of web pages that discuss the various libraries, I decided to 


concentrate on the json-simple library in this book. For example, here is the 
conclusion from the article titled A Review of 5 Java JSON Libraries : 


Note: 

"If you are looking for a simple lightweight Java library that reads and 
writes JSON, and supports Streams, JSON.simple is probably a good 
match. It does what it says on the box in 12 classes, and works on legacy 
(1.4) JREs. " 


This conclusion is similar to conclusions that I found on several other 
websites. However, you should not take my selection of json-simple for this 
book as a recommendation for the json-simple library as compared to other 
libraries that are available. Once you have a basic understanding of how to 
process JSON using Java and the json-simple library, you should conduct 
your own review to identify the library that best suits your needs. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view Figure 
1 while you are reading about it. 


Background information 


JSON is an acronym for JavaScript Object Notation . Don't be fooled by 
the name however. Although JSON is based on JavaScript object syntax, it 
is not JavaScript nor is it any programming language. As stated earlier, 
JSON is simply a lightweight, text-based, language-independent data 
interchange format -- nothing more and nothing less. 


A lightweight text-based data interchange format 


Similar to XML, JSON is a general purpose data interchange format that is 
supported by Java, PHP, JavaScript, and other programming languages. 
JSON is a standard that describes how ordered lists and unordered maps, 
strings, boolean values, and numbers can be represented as text in a string. 


Similar to but less complex than XML, JSON provides a way to pass 
structured information between different computing environments using the 
same or different languages. 


Typical operation 


Typically a data construct, (such as an object for example) , in one 
programming environment will be transformed into a JSON string. That 
string will be transported to another programming environment where it 
will be transformed into a data construct, (such as a hash table for example) 
, that is suitable for use in that programming environment 


A real-world analogy 


Consider the following analogous situation. A young family has a large 
playscape for their children in their back yard. They need to move to 
another house across town. In order to save money, they rent a small truck 
and do the entire move themselves. 


A playscape object 


The playscape can be thought of as an object with certain properties such as 
swing and slide . 


It is too large to fit into the truck so the adults disassemble it into a well- 
organized package of boards, chains, bolts, nuts, etc. They are very careful 


to label each part and to create some drawings showing the organization of 
the parts for use later. 


No longer an object 


In that disassembled state, it can no longer be thought of as an object with 
properties of swing and slide . Instead, it is simply a well-organized and 
documented package of parts. The package of parts is analogous to a JSON 
string. The playscape object has been transformed into a well-organized 
package of parts. 


Reassemble the parts 


After the parts are transported to the new location, they are reassembled 
into an object with properties of swing and slide . 


This is what we do with JSON. We disassemble an object (or other data 
construct) into a JSON string: a well-organized package of parts. Later on, 
and possibly in an entirely different programming environment, we 
reassemble the parts into a data construct suitable for use in the new 
programming environment. 


Streamlined procedures 


Java, JavaScript, PHP, and other programming languages provide 
streamlined procedures for transforming a data construct into a JSON string 
and for transforming a JSON string into a suitable data construct. As an 
example, the toJASONString method can be used to transform a Java 
object of type JSONObject into a JSON string. The parse method of the 
Java JSONValue class can be used to transform a JSON string into a 
JSONObject object. Other methods or functions are available to 
accomplish the same purposes in other languages such as JavaScript . 


Online references 
There are many good online JSON references. Here are a few: 


e Introducing JSON 

¢ The json-simple library 

e JSON: The Fat-Free Alternative to XML 

e Java API for JSON Processing: An Introduction to JSON 

¢ JSON with PHP 

e JSON tutorial for beginners learn how to program part 1 JavaScript 
(video) 

e JSON in JavaScript 

e JSON: What It Is, How It Works, How to Use It 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0200: The What and Why of JSON 
e File: Json0200.htm 
e Published: 05/29/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 


In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0200R: Review 

This page contains review questions and answers for the page titled 
"Json0200 The What and Why of JSON" in the book titled "The json- 
simple Java Library". 


Revised: Fri Jun 03 14:06:45 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


© Question 1 
© Question 2 
© Question 3 
© Question 4 
© Question 5 
© Question 6 
© Question 7 
© Question 8 


e Figure index 
e Answers 


Answer 8 
Answer 7 
Answer 6 
Answer 5 
Answer 4 
Answer 3 
Answer 2 


o Oo 0 0 0 0 90 


o Answer 1 


e Figures 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0200 The What and Why of JSON . Once 
you study that page, you should be able to answer the review questions in 
this page. 


The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 

The Figures and Listings (if any) are grouped together. It is recommend that 
when a question or an answer refers to a Figure or a Listing, that you open 


it in anew window to make it easy to view it while reading the question or 
the answer. 


Questions 


Question 1. 
True or False? JSON is an acronym for "Java Object Names." 


Go to answer 1 


Question 2 


True or False? JSON is based on a subset of the JavaScript Programming 
Language. 


Go to answer 2 


Question 3 


True or False? JSON is a text format that is language independent but uses 
conventions that are familiar to programmers of the C-family of languages 
including C, C++, C#, Java, JavaScript, Perl, Python, Visual Basic, and 
many others. 


Go to answer 3 


Question 4 
True or False? JSON is part of the JavaScript programming language. 


Go to answer 4 


Question 5 


True or False? JSON can represent three structured types: objects, arrays, 
and conditionals. 


Go to answer 5 


Question 6 


True or False? Figure 1 shows a JSON text string containing name/value 
pairs as well as nested arrays. 


Go to answer 6 


Question 7 


True or False? JSON is important in the implementation of Big Data 
NoSQL databases such as MongoDB and Couchbase . 


Go to answer 7 


Question 8 
True or False? This book is intended to teach you about JSON. 


Go to answer 8 


Figure index 
e Figure 1 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None Cox) 
Display your namesheke. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


ProbO05a.jpg 
Put your name here 


Answers 


Answer 8 


False. This book is not intended to teach you about JSON. There are 
numerous tutorials on the web that you can access for that purpose. This 
book is intended to teach you how to use the json-simple Java library, 
(which is one of several available libraries), to parse, generate, transform, 
and query JSON. 


Go back to Question 8 


Answer 7 


True. According to the InfoWorld article of August 25, 2014, "Several 
NoSQL databases -- including the wildly successful MongoDB and 
Couchbase -- store data in JSON documents natively." 


Go back to Question 7 


Answer 6 
True. 


Go back to Question 6 


Answer 5 


False. According to the online document titled Java API for JSON 
Processing: An Introduction to JSON , "JSON can represent two structured 
types: objects and arrays. An object is an unordered collection of zero or 
more name/value pairs. An array is an ordered sequence of zero or more 
values. The values can be strings, numbers, booleans, null, and these two 
structured types." 


Go back to Question 5 


Answer 4 


False. It is important to note that even though JSON is based on JavaScript 
syntax, JASON is not JavaScript nor is it any other programming language. 
In fact, it is not a programming language at all. JSON is simply "a 
lightweight, text-based, language-independent data exchange format" -- 
nothing more and nothing less. 


Go back to Question 4 


Answer 3 


False. Visual Basic is not based on the C-family of languages. Visual Basic 
is based on the BASIC programming language that came into existence in 
1964. The C programming language came into existence independently in 
1972. 


Go back to Question 3 


Answer 2 
True. 


Go back to Question 2 


Answer 1 


False. According to the online document titled Introducing JSON. "JSON 
(JavaScript Object Notation) is a...". 


Go back to Question 1 


Figures 


This section contains Figures that may be referred to by one or more 
questions or answers. These Figures may also be helpful as reference 
material for answering the questions. 


Note: Figure 1. 


t 


"game": 


{"cards": 


[ 


"2-club","3-heart","4-diamond", "5-spade" 


i 
"name":"Tom" 
i 
+ Candso 
"4-heart", "5-heart", "6-club", '"7-diamond" 
i 
"name": "Joe" 
} 
| 
} 
Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0200R: Review 
e File: Json0200R.htm 
e Published: 06/03/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 


I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0205: Getting Started 
Learn how to download, install, and test the json-simple Java library. 


Revised: Thu Jun 02 19:21:59 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


e Table of contents 
e Preface 


o Viewing tip 


=» Figures 
= Listings 


e The json-simple library 


Download the library 
Library documentation 
Install the library 

Test your installation 


o Oo 0 90 


e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page explains how to get started 
using the library. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Output from test program. 


Listings 


e Listing 1. Java test program. 
¢ Listing 2.. Sample batch file. 


The json-simple library 


Download the library 


As of May 2016, the library can be downloaded in a jar file named json- 
simple-1.1.1.jar . The name of the jar file may be expected to change over 
time as new versions are released. 


Library documentation 


Also as of May 2016, a file named json_simple-1.1-all.zip , which contains 
source code for the library, can be downloaded from that same page. See the 
contents of that zip file for a copy of the license covering the material in the 
library. 


I used the source code from that file to create a documentation package for 
version 1.1, which you can download here . Download and extract the 
contents of the file named docs.zip into an empty folder and open the file 


named index.html in your browser to view the documentation in standard 
javadoc format. 


Install the library 


To use the library, you need to download the latest version of the jar file, 
store it somewhere on your system, and put it on your classpath. The 
instructions on this page apply to Windows 7. If you are using some other 
operating system, you will need to adjust the instructions to make them 
compatible with your operating system. 


Test your installation 


Create a Java source code file named Code containing the code shown in 
Listing 1 and store it in a folder somewhere on your system. 


Note: Listing 1 . Java test program. 


PAG eM SSS RSD T SoBe Eas eee ae IgA NR RS a Sa dee ail te need een lass a) 
KKK 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1.jar 

KKEKEKEKKRKEKRKEKR KEKE KERR KERR KEKE KEKE KEKE KER KEKE KEKE KEKE KEKE KEK KEKE KEKE KEKE KEKE EE 
sey fe 


import org.json.simple.ItemList; 


Class Code{ 
public static void main(String[] args){ 
System.out.println("ItemList: " + new 

ItemList(). 


getClass().getSuperclass()); 


}//end main 
}//end class code 


Assuming that you have downloaded the jar file and stored it in a folder 
named json-simple in the root directory of your C drive, create a batch file 
containing the commands shown in Listing 2 and store the batch file in the 
same folder as the source code file named Code . 


Note: Listing 2 . Sample batch file. 


echo off 
rem Sets the classpath, compiles, and runs 
Code. java. 


del *.class 


javac -cp .;C:\json-simple\json-simple-1.1.1.jar 
Code.java 


java -cp .;C:\json-simple\json-simple-1.1.1.jar 
Code 
pause 


Double-click the batch file. Assuming that you have a compatible version 
of the Java Development Kit installed on your system, your test program 
should be compiled and executed, producing the output shown in Figure 1 
on your computer screen. 


Note: Figure 1. Output from test program. 


ItemList: class java.lang.Object 
Press any key to continue 


By way of explanation, the code in Listing 1 instantiates a new object of the 
class named ItemList from the JSON library. Then it gets and displays the 
superclass of that class, which is the class named Object . In other words, 
the JSON library class named ItemList extends the standard class named 
Object . 


If you were able to produce the output shown in Figure 1 , you are ready to 
Start generating, transforming, and querying JSON text using Java and the 
json-simple Java library. 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0205: Getting Started 
e File: Json0205.htm 
e Published: 05/30/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 


should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : : 1 am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0205R: Review 

This page contains review questions and answers for the page titled 
"Json0205 Getting Started" in the book titled "The json-simple Java 
Library". 


Revised: Fri Jun 03 14:54:03 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming_(QOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


© Question 1 
© Question 2 


e Answers 


o Answer 2 
o Answer 1 


e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0205: Getting Started . Once you study that 
page, you should be able to answer the review questions in this page. 


The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 


Questions 


Question 1. 
True or False? To use the library, you need to download the latest version of 
the jar file, store it somewhere on your system, and put it on your operating 


system's path environment variable. 


Go to answer 1 


Question 2 


True or False? The json-simple library class named ItemList extends the 
standard Java class named ArrayList . 


Go to answer 2 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None eles 


Display your namethieke. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 2 


False. The json-simple library class named ItemList extends the standard 
Java class named Object . 


Go back to Question 2 


Answer 1 


False. To use the library, you need to download the latest version of the jar 
file, store it somewhere on your system, and put it on your operating 
system's classpath environment variable. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0205R: Review 
e File: Json0205R.htm 
e Published: 06/03/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 


nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0210: Structure of the json-simple Java Library 
This page explains the inheritance structure of the json-simple Java library 
and how it fits into the standard Java library. 


Revised: Thu Jun 02 19:23:22 CDT 2016 
This page is included in the following Books: 
¢ The json-simple Java Library. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


e Table of contents 
e Preface 


o Viewing tip 


=» Figures 
= Listings 


¢ General background information 
e Discussion and sample code 

e What you can expect 

e Run the program 

¢ Complete program listing 

e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page explains the inheritance 
structure of the json-simple Java library and how it fits into the standard 
Java library. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Inheritance hierarchy. 


Listings 


e Listing 1. Program named Code.java. 


General background information 


The earlier page titled Json0205: Getting Started provided a download link 
for a standard javadoc documentation package for version 1.1 of the json- 
simple Java library. That documentation package shows that the library 
contains the following packages: 


° org.json.simple 
° org.json.simple.parser 


Those packages contain the following classes and interfaces with the 
interfaces shown in Italics : 


e ContainerFactory 
e ContentHandler 

e ItemList 

e JSONArray 

e JSONAware 

e JSONObject 

e JSONParser 

e JSONStreamAware 


e JSONValue 
e ParseException 
e Yytoken 


Note: 

The jar file also contains a class named Yylex in the 
org.json.simple.parser package that did not show up in the 
documentation. It didn't show up in the documentation because it is 
package-private and therefore not intended for our direct use. It is used 
internally by code in the class named JSONParser . 


Discussion and sample code 


Listing 1 provides the code for a Java program that establishes the position 
in the class hierarchy of each of the classes in the json-simple library by 
displaying the superclass of each of those classes. Figure 1 shows the screen 
output produced by this program. 


Note: Figure 1. Inheritance hierarchy. 


ItemList: class java.lang.Object 
JSONArray: class java.util.ArrayList 
JSONObject: class java.util.HashMap 
JSONParser: class java.lang.Object 
JSONValue: class java.lang.Object 
ParseException: class java.lang.Exception 
Yytoken: class java.lang.Object 


The class named ParseException extends the standard class named 
Exception as you might expect. 


Four of the classes extend the class named Object , which is not 
particularly surprising. New classes extend the Object class by default 
unless they are defined to purposely extend some other class. 


The most important thing shown in Figure 1 is that the JSONArray class 
extends the standard ArrayList class and the JSONObject class extends 
the standard HashMap class. These standard classes are part of the Java 

Collections Framework . 


This illustrates one of the most important features of the json-simple 
library. The library maximizes the use of standard classes from the Java 
Collections Framework . Once you have a reference to an object of the 
JSONArray class or an object of the JSONObject class, you have access 
to all of the polymorphic features provided by that framework. You also 
have access to the methods defined by those two classes and the classes 
defined by their superclasses. Therefore, if you are already skilled at 
programming within the collections framework, it is a small step to add 
JSON programming to your skill set. 


What you can expect 


This book will explain how to use the following classes: 


e JSONObject 

e JSONValue 

e JSONParser 

e JSONArray 

e ParseException 


An investigation into the use of the other classes and interfaces will be left 
as "an exercise for the student" . 


Run the program 


I encourage you to copy the code from Listing 1. Execute the code and 
confirm that you get the same results as those shown in Figure 1 . 
Experiment with the code, making changes, and observing the results of 
your changes. Make certain that you can explain why your changes behave 
as they do. 


Complete program listing 


Listing 1 provides the source code for the program named Code.java . 


Note: Listing 1 . Program named Code.java. 


rs eR ai Ie Peet Me MI Ree A a A eRe ae thee ee Ria ee eke 


KKEKKKKKEKKKKEKRKEKKKEKEKSE 


Copyright 2016, R.G.Baldwin 

Establishes the position of each of the json- 
simple classes in the 

Class hierarchy by getting and displaying the 
superclass of each 

class. 


Produces the following output: 


ItemList: class java.lang.Object 
JSONArray: class java.util.ArrayList 
JSONObject: class java.util.HashMap 
JSONParser: class java.lang.Object 
JSONValue: class java.lang.Object 
ParseException: class java.lang.Exception 
Yytoken: class java.lang.Object 


Tested with Java 8, Windows 7, and json-simple- 
eae jak 


KKEKKKRKKEKKRKKEKE KEKE KK KEKE KEKE KEKE REE KK KEKE KEKE KEKE KEKE KKK KEKE KKK 


RNa hh ear ech nae ane 


import org.json.simple.JSONObject; 

import org.json.simple.JSONArray; 

import org.json.simple.JSONValue; 

import org.json.simple.ItemList; 

import org.json.simple.JSONAware; 

import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 
import org.json.simple.parser.Yytoken; 


Class Code{ 
public static void main(String[] args){ 


System.out.printiln("ItemList: " + 
new 
ItemList().getClass().getSuperclass()); 
System.out.printin("JSONArray: " + 
new 
JSONArray().getClass().getSuperclass()); 
System.out.println("JSONObject: " + 
new 
JSONObject().getClass().getSuperclass()); 
System.out.printiln("JSONParser: " + 
new 
JSONParser().getClass().getSuperclass()); 
System.out.println("JSONValue: " + 


new 
JSONValue().getClass().getSuperclass()); 
System.out.printiln("ParseException: " + 


new 
ParseException(ParseException.ERROR_UNEXPECTED_CHA 
R). 


getClass().getSuperclass()); 
System.out.println("Yytoken: " + 
new 


Yytoken(Yytoken.TYPE_COLON,":"). 


getClass().getSuperclass()); 
}//end main 
}//end class code 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


¢ Module name: Json0O210: Structure of the json-simple Java Library 
e File: Json0210.htm 
e Published: 05/30/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 


on cnx.org and that it was made and published without my prior 


knowledge. 
Affiliation : I am a professor of Computer Information Technology at 


Austin Community College in Austin, TX. 


-end- 


Json0210R: Review 

This page contains review questions and answers for the page titled 
"Json0210: Structure of the json-simple Java Library" in the book titled 
"The json-simple Java Library”. 


Revised: Fri Jun 03 17:21:17 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


Question 1 
Question 2 
Question 3 
Question 4 
Question 5 
Question 6 
Question 7 
Question 8 
Question 9 
Question 10 


O° 
(e) 
ie) 
10) 
10) 
10) 
(0) 
(2) 
°O 
(e) 


e Answers 


Answer 10 
Answer 9 
Answer 8 
Answer 7 
Answer 6 
Answer_5 


o Oo 0 0 0 0 


o Answer 4 
o Answer 3 
o Answer 2 
o Answer 1 


e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0210: Structure of the json-simple Java 
Library_. Once you study that page, you should be able to answer the review 
questions in this page. 


The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 


Questions 


Question 1. 


True or False? Version 1.1 of the json-simple Java library contains the 
following packages: 


° org.json.simple 
° org.json.simple.parser 


Go to answer 1 


Question 2 


True or False? Version 1.1 of the json-simple Java library contains the 
public classes shown below 


e ItemList 

e JSONArray 

e¢ JSONObject 

e JSONParser 

e JSONValue 

e ParseException 
e Object 

e« Yytoken 


Go to answer 2 


Question 3 


True or False? Version 1.1 of the json-simple Java library contains a class 
named Yylex in the org.json.simple.parser package that is declared to be 
package-private . 


Go to answer 3 


Question 4 


True or False? Despite its name, the JSONArray class is not really an 
array. Instead, it is a List . 


Go to answer 4 


Question 5 


True or False? Objects of the JsONArray class contain unordered data. 


Go to answer 5 


Question 6 


True or False? Other than the JSONObject class and the JsONArray 
class, all of the classes in version 1.1 of the json-simple Java library extend 
the Object class. 


Go to answer 6 


Question 7 


True or False? The JSONObject class extends the standard Java TreeSet 
class. 


Go to answer 7 


Question 8 


True or False? An object of the JsSONObject class maps keys or names to 
values . 


Go to answer 8 


Question 9 


True or False? An object of the JSONObject class can contain duplicate 
keys but cannot contain duplicate values. 


Go to answer 9 


Question 10 


True or False? An object of the JSONObject class is an unordered 
collection. 


Go to answer 10 
What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


FB None rer 
Display your name here 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 10 


True. An object of the JSONObject class extends the HashMap class and 
implements the Map interface. According to the Oracle documentation, 
"The order of a map is defined as the order in which the iterators on the 
map's collection views return their elements. Some map implementations, 
like the TreeMap class, make specific guarantees as to their order; others, 
like the HashMap class, do not." 


Go back to Question 10 


Answer 9 


False. The JSONObject class implements the Map interface. According to 
the Oracle documentation, "A map cannot contain duplicate keys; each key 
can map to at most one value." 


Go back to Question 9 


Answer 8 


True. JSON documentation often speaks of name/value pairs. However, the 
JSONObject class extends the standard Java HashMap class, which 
implements the Map interface. According to the Oracle Java 
documentation, an object that implements the Map interface is "An object 
that maps keys to values." Therefore, it is probably acceptable to use the 
terms name/value and key/value interchangeably. 


Go back to Question 8 


Answer 7 
False. The JSONObject class extends the standard Java HashMap class. 


Go back to Question 7 


Answer 6 
True. 


Go back to Question 6 


Answer 5 


False. Because the JSONArray class extends the ArrayList class, which 
implements the List interface, it is "An ordered collection (also known as a 
sequence). The user of this interface has precise control over where in the 
list each element is inserted. The user can access elements by their integer 
index (position in the list), and search for elements in the list." 


Go back to Question 5 


Answer 4 


True. The JSONArray class extends the standard ArrayList class, which 
implements the List interface. 


Go back to Question 4 


Answer 3 
True. 


Go back to Question 3 


Answer 2 


False. Version 1.1 of the json-simple Java library does not contain a class 
named Object . 


Go back to Question 2 


Answer 1 
True. 


Go back to Question 1 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0210R: Review 
e File: Json0210R.htm 
e Published: 06/03/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0215: Encoding JSON Strings 
Learn how to use the JSONObject class to encode key/value pairs into 
JSON strings. 


Revised: Thu Jun 02 19:24:40 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library.. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


e Table of contents 
e Preface 


o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


Create ArrayList containers 


Encode the data into JSON strings 
Display the JSON strings 
The end of the program 


0 00000 
e. 
la \ 
iD 
ee) 
(om 
io 
io 
~ 
fs 
re) 
iO 
jC 
= 
s 
> 
(om 
io 
i 
< 
‘=; 
Oo 
Le} 
fc) 
= 
IW 
CO 
ra 
OC 
oJ, 
i 
a 
i 
Oo 
WJ, 
iD 
A 
(oma 
a 


e Run the program 
¢ Complete program listing 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page explains how to use the 
JSONObject class to encode key/value pairs into JSON strings. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. The screen output. 


Listings 


e Listing 1. Create ArrayList containers. 

e Listing 2.. Create and populate a JSONObject object. 

e Listing 3. Create and populate two more JSONObject objects. 
e Listing 4. Encode the data into JSON strings. 

e Listing 5. Display the JSON strings. 

e Listing 6. The program named Code.java. 


General background information 


As you learned in the earlier page titled Json0210: Structure of the json- 
simple Java Library_, the class named JSONObject extends the standard 
Java class named HashMap . Therefore, once you have an object of the 
class named JSONObject , you can call any of the methods defined in or 
inherited into the JsONObject class on that object. 


In the sample program that follows, we will use the put method that is 
inherited from the HashMap class to populate the object with key/value 
pairs. We will use the toJSONString method that is defined in the 
JSONObject class to transform the populated object into a JSON string. 


Discussion and sample code 


The program named Code (see Listing_6_) constructs three JSONObject 
objects, populates the objects with key/value pairs, and saves the 
JSONObject objects in an ArrayList object. (Actually it saves references 
to the JSONObject objects in the ArrayList object.) 


Then it transforms each JSONObject object into a JSON string. At this 
point, the JSON strings could be written to an output stream and transferred 
to a different programming environment. However, to keep the program 
simple, the program simply saves the JSON strings in a second ArrayList 
object for later display. 


Then the program displays the JSON strings for comparison with the code 
that populated the JSONObject objects in the first place. 


Create ArrayList containers 


A complete listing of the program named Code is provided in Listing 6 near 
the end of the page. I will discuss and explain the code in fragments. The 
first fragment is shown in Listing 1. 


Note: Listing 1 . Create ArrayList containers. 


import org.json.simple.JSONObject; 
import java.util.ArrayList; 
import java.util.Iterator; 


Class Code { 


public static void main(String[] args) { 
//Create a container for several JSON objects. 
ArrayList <JSONObject> listA = new 
ArrayList<JSONObject>(); 
//Create a container for several JSON strings 
ArrayList <String> listB = new 
ArrayList<String>(); 


The code in Listing 1 instantiates two objects of the class named ArrayList 
to serve as containers for the JsONObject objects and the JSON strings. 
This is plain vanilla Java code. There is nothing new here. 


Create and populate a JSONObject object 


Listing 2 creates and populates the first JsONObject object with key/value 
pairs. The keys are "name", "age", and "student" respectively. The value 
types are String , int , and boolean respectively. 


Note: Listing 2 . Create and populate a JsONObject object. 


listA.add(new JSONObject()); 


listA.get(0).put("name", "Joe"); 
listA.get(0).put("age", 21); 
listA.get(0).put("student", true); 


The code in Listing 2 begins by instantiating a new object of the 
JSONObject class and adding its reference into the first element (0) of the 
ArrayList object. Then it calls the get method on the ArrayList object 
three times in succession to gain access to the JsONObject . Each time it 
gains access to the JSONObject object, it calls the put method inherited 
from the HashMap class to store a key/value pair in the JSONObject 
object. 


Note: 

Note that the data stored in the JSONObject object is an unordered 
collection. As you will see later, the order in which the key/value pairs are 
extracted from the object using an iterator is unrelated to the order in 
which the key/value pairs are stored in the object. 


Create and populate two more JSONObject objects 


Listing 3 repeats the process two more times to create, populate, and save 
two more JSONObject objects. Note that one of these objects is populated 
in a different order than is the case in Listing 2 . 


Note: Listing 3 . Create and populate two more JSONObject objects. 


//Create and populate the second JSONObject. 
listA.add(new JSONObject()); 
listA.get(1).put("student", false); 
listA.get(1).put("name", "Sue"); 
listA.get(1).put("age", 32); 


//Create and populate the third JSONObject 
listA.add(new JSONObject()); 


listA.get(2).put("name", "Tom"); 
listA.get(2).put("age",19); 
listA.get(2).put( "student", true); 


Encode the data into JSON strings 


Listing 4 uses an Iterator to gain access to each populated JSONObject 
object. Each time it gains access to an object, it calls the toJSONString 
method that is defined in the JSONObject class to transform the object into 
a JSON string. 


At this point, the program could write the JSON strings into an output 
stream for transfer to some other programming environment. However as 
mentioned earlier, to keep the program simple, the program saves the JSON 
strings as elements in a second ArrayList object. 


Note: Listing 4 . Encode the data into JSON strings. 


Iterator<JSONObject> iteratorA = 
listA.iterator(); 
while (iteratorA.hasNext()){ 
listB.add(iteratorA.next().toJSONString()); 
}//end while loop 


Display the JSON strings 


Listing 5 uses an Iterator to access and display each of the JSON strings 
that are stored in the ArrayList object. 


Note: Listing 5 . Display the JSON strings. 


Iterator<String> iteratorB = listB.iterator(); 

while (iteratorB.hasNext()){ 
System.out.println(iteratorB.next()); 

}//end while loop 


}//end main 
}//end class Code 


The screen output is shown in Figure 1. 


Note: Figure 1. The screen output. 


{"student":true, "name": "Joe", "age":21} 
{"student":false, "name": "Sue", "age" :32} 
{"student":true, "name": "Tom", "age":19} 


The format for each line of text that you see in Figure 1 is the format that 
you would expect for a JSON string that doesn't include array data. (See 
Introducing JSON for more details regarding format.) 


Briefly, each key is separated from its value by a colon (:) . Each key/value 
pair is separated from its neighbors by a comma (,) . The JSON string 
begins with a left brace ({) and ends with a right brace (}) . Keys are 
surrounded by double quotation characters. Values may or may not be 
separated by double quotation characters, depending on their type. Some 


characters inside of values, such as double quotation characters and 
backslash characters must be escaped with a backslash character (\" and \\) 
but that is not shown by this program. 


Note that the display order for the key/value pairs shown in Figure 1 does 
not match the order in which the objects were populated in Listing 2 and 
Listing 3.. A HashMap does not impose an ordering on its contents and 
does not guarantee that the ordering will remain constant over time. 


The end of the program 


Listing 5 also signals the end of the main method and the end of the 
program. 


Run the program 


I encourage you to copy the code from Listing 6. Execute the code and 
confirm that you get the same results as those shown in Figure 1. 
Experiment with the code, making changes, and observing the results of 
your changes. Make certain that you can explain why your changes behave 
as they do. 


Complete program listing 


A complete listing of the program named Code.java is provided in Listing 6 


Note: Listing 6. The program named Code.java. 


ay Oe Oe ah ek Ra a i a a he ah 


KRKEKEKKKKEKKRKEKKEKEKEKEKKESE 


Copyright 2016 R.G.Baldwin 


Constructs three JSONObject objects and saves them 
in an ArrayList. 
Transforms each JSONObject object into a String 
object and saves the 

strings in a second ArrayList object. 

Displays the strings. 


Tested with Java 8, Win 7, and json-simple- 
a ie lps Leg Ur 8 


KRKEKEKKRKKEKRKEKRKRKEKEKEKRKRKEK KERR KR KERR KEKE KERR KEKE KEK KEK KRKEKKEKRKEKKEKEEKESE 


ROR RUE RA Rak ont hie rea, 


import org.json.simple.JSONObject; 
import java.util.ArrayList; 
import java.util.Iterator; 


Class Code { 


public static void main(String[] args){ 
//Create a container for several JSON objects. 
ArrayList <JSONObject> listA = new 
ArrayList<JSONObject>(); 
//Create a container for several JSON strings 
ArrayList <String> listB = new 
ArrayList<String>(); 


//Create and populate the first JSONObject 
with unordered 

// key/value pairs. 

listA.add(new JSONObject()); 

listA.get(0).put("name", "Joe"); 

listA.get(0).put("age", 21); 

listA.get(0).put("student", true); 


//Create and populate the second JSONObject. 
Note that the object 


// 1s populated in a different order than 
above. 

listA.add(new JSONObject()); 

listA.get(1).put("student", false); 

listA.get(1).put("name", "Sue"); 

listA.get(1).put("age", 32); 


//Create and populate the third JSONObject 
listA.add(new JSONObject()); 
listA.get(2).put("name","Tom"); 
listA.get(2).put("age",19); 
listA.get(2).put("student", true); 


//Transform the three JSON objects into JSON 
strings and save 

// them in ListB. Could write them to disk for 
transfer toa 

// different programming environment at this 
point. 

Iterator<JSONObject> iteratorA = 
listA.iterator(); 

while (iteratorA.hasNext()){ 

listB.add(iteratorA.next().toJSONString()); 
}//end while loop 


//Display the JSON strings currently stored in 
listB. Note that 

// the display order does not necessarily 
match the order in 

// which the original objects were populated. 

Iterator<String> iteratorB = listB.iterator(); 

while (iteratorB.hasNext()){ 

System.out.printiln(iteratorB.next()); 
}//end while loop 


}//end main 
}//end class Code 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e¢ Module name: Json0215: Encoding JSON Strings 
e File: Json0215.htm 
e Published: 05/31/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : | am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0215R: Review 

This page contains review questions and answers for the page titled 
"Json0215: Encoding JSON Strings" in the book titled "The json-simple 
Java Library". 


Revised: Sat Jun 04 12:48:39 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


© Question 1 
© Question 2 
© Question 3 


e Figure index 
e Listing index 
e Answers 


o Answer 3 
o Answer 2 
o Answer 1 


e Figures 


e Listings 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0215: Encoding JSON Strings . Once you 
study that page, you should be able to answer the review questions in this 
page. 

The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 

The figures and listings (if any) are grouped together. It is recommend that 
when a question or an answer refers to a figure or a listing, that you open it 


in anew window to make it easy to view it while reading the question or 
the answer. 


Questions 


Question 1. 

True or False? Once you have an object of the class named JSONObject , 
you can call any of the methods defined in the HashMap class on that 
object. 


Go to answer 1 


Question 2 


True or False? The code shown in Listing 1 produced the screen output 
shown in Figure 1 . 


Go to answer 2 


Question 3 


True or False? The code shown in Listing 3 produced the screen output 
shown in Figure 3 . 


Go to answer 3 


Figure index 


e Figure 1 
e Figure 2 
e Figure 3 


Listing index 


e Listing 1 
e Listing 2 
e Listing 3 


What is the meaning of the following two images? 
These images were inserted here simply to insert some space between the 


questions and the answers to keep them from being visible on the screen at 
the same time. 


None - jo\x) 
Display your name here. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


ProbO05a.jpg 
Put your name here 


Answers 


Answer 3 


True. The code in Listing 3 uses the get method inherited from the 
HashMap class to get and display the values associated with the keys 


"name", "age", and "student". 


Go back to Question 3 


Answer 2 


False. The code in Listing 1 produced the output with the compiler error 
message shown in Figure 2. The output shown in in Figure 1 was produced 
by the code shown in Listing 2. Note the call to the toJSONString method 
of the JSONObject class to extract the information from the JSONObject 
object and encode it into a JSON string. 


Go back to Question 2 


Answer 1 

True. The class named JSONObject extends the standard Java class named 
HashMap . Therefore, the JSONObject class inherits all of the methods 
defined in the HashMap class. 


Go back to Question 1 


Figures 


This section contains Figures that may be referred to by one or more 
questions or answers. 


Note: 
Figure 1 


{"student":true, "name":"Joe","age":21} 


Note: 


Figure 2 


Code01.java:20: error: no suitable method found 
for get(no arguments) 
String jsonString = jsonObject.get(); 


Note: 
Figure 3 


Joe 
21 
true 


Listings 


This section contains Listings that may be referred to by one or more 
questions or answers. 


Note: 

Listing 1 

import org.json.simple.JSONObject; 

class Code0i { 

public static void main(String[] args){ 

JSONObject jsonObject= new JSONObject(); 
jsonObject.put("name", "Joe"); 
jsonObject.put("age",21); 
jsonObject.put("student", true); 


String jsonString = jsonObject.get(); 
System.out.println(jsonString) ; 


}//end main 
}//end class Code01 


Note: 

Listing 2 

import org.json.simple.JSONObject; 

Class Code02 { 

public static void main(String[] args){ 

JSONObject jsonObject= new JSONObject(); 
jsonObject.put("name", "Joe"); 
jsonObject.put("age", 21); 
jsonObject.put("student", true); 


String jsonString = jsonObject.toJSONString(); 
System.out.println(jsonString); 


}//end main 
}//end class Code02 


Note: 

Listing 3 

import org.json.simple.JSONObject; 
Class Code03 { 


public static void main(String[] args) { 


JSONObject jsonObject= new JSONObject(); 
jsonObject.put( "name", "Joe"); 
jsonObject.put("age",21); 
jsonObject.put("student", true); 


System.out.println(jsonObject.get("name")); 
System.out.println(jsonObject.get("age")); 
System.out.println(jsonObject.get("student")); 


}//end main 
}//end class Code03 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0215R: Review 
e File: Json0215R.htm 
e Published: 06/04/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 


In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0220: Decoding JSON Strings 
Learn to decode JSON strings using the parse methods of the JSONValue 
and JSONParser classes. 


Revised: Thu Jun 02 19:25:56 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library.. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


e Table of contents 
e Preface 


o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


Decode and display using the JSON Value class 
The method named decodeC 

Decode and display using the J SONParser class 
The method named decodeD 

The end of the program 


oO 0 0 0 0 O 
|S) 
—e 
2) 
ne) 
— 
fab) 
a 
(a) 
iO 
=} 
fg 
eo) 
=} 
— 
IW 
iO 
—_— 
—_— 
IW 
O 
Z 
O 
oO 
Cel © 
[s>) 
(a) 
(om 
iO 
IS- 
(a>) 
ae) 
— 
IW 


e Run the program 
¢ Complete program listing 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page explains how to decode JSON 
strings using the parse methods of the JsONValue and JSONParser 
classes. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Program output. 


Listings 


e Listing 1. Decode and display using the JSON Value class. 
e Listing 2. The method named decodeC. 

e Listing 3. The display method. 

e Listing 4. Decode and display using the JSONParser class. 
e Listing 5. The method named decodeD. 

e Listing 6. The program named Code.java. 


General background information 


As mentioned in the Preface , this page deals with the classes named 
JSONValue and JSONParser . Each of these classes extends the Object 
class and provides various methods for processing JSON data. The page 
also exposes you to the class named ParseException . 


All of the methods in the JSONValue class are static methods. Methods in 
this class are available to deal with JSON input data in both the string 
format and the JSONObject format. 


None of the methods in the JSONParser class are static methods. In 
general the methods in this class are designed to deal only with input data in 
the string format. 


Both classes provide several overloaded parse methods that can be used to 
parse input JSON text from different sources into the JSONObject format. 


The sample program that follows will use the parse method from both 
classes to parse JSON strings into JSONObject objects. 


Discussion and sample code 


The program named Code (see Listing_6_) consists of some old code and 
some new code. The program begins just like the program that I explained 
in the earlier page titled Json0215: Encoding JSON Strings . The beginning 
portion of the program is used solely to create JSON data in string format 
and to store the individual strings as elements in an ArrayList object. 


This code constructs three JSONObject objects and saves them in an 
ArrayList object. Then it transforms each JSONObject object into a 
String object and saves the strings in a second ArrayList object. The new 
code decodes the strings into JSONObject objects using a parse method 
from the JSONValue class and saves them in a third ArrayList object. 


Then the new code decodes the strings into JSONObject objects using a 
parse method from the JSONParser class and saves them in a fourth 
ArrayList object. 


The contents of both lists of JSONObject objects are displayed on the 
computer screen after they are populated with decoded data from the JSON 
strings. 


Decode and display using the JSONValue class 


I will explain this program in fragments, and will begin at the point where 
the new code begins. The first fragment is shown in Listing 1 . 


Note: Listing 1 . Decode and display using the JsONValue class. 


//Create a container for decoded JSON strings. 
ArrayList <JSONObject> listC = new 
ArrayList<JSONObject>(); 


//Decode and display JSON strings using the 
parse method of the 

// JSONValue class 

System.out.println( "Decode using JSONValue 
class"); 

decodeC(listB, listC); 

display(listcC); 

System.out.printin();//blank line 


Immediately prior to the code in Listing 1, three JSON strings are stored as 
elements in an ArrayList object referred to as listB . 


Listing 1 begins by instantiating a new ArrayList object, referred to as 
listC that will receive the decoded versions of the JSON strings as type 
JSONObject objects. Then Listing 1 calls the method named decodeC 
passing the list of JSON strings and the empty list as parameters. 


The method named decodeC 


The method named decodeC is shown in its entirety in Listing 2. 


Note: Listing 2 . The method named decodeC. 


static void decodeC(ArrayList input, ArrayList 
output ){ 
String temp = null; 
Iterator<String> iterator = input.iterator(); 
while (iterator.hasNext()){ 
temp = iterator.next(); 
output .add(JSONValue.parse(temp) ); 
}//end while loop 
}//end decodeC 


This method decodes a list of JSON strings into JsONObject objects using 
a Static parse method of the JSONValue class. The resulting JsONObject 
objects are added to the empty ArrayList object received as an incoming 
parameter. When the method returns, that list contains one JSONObject 
object for each JSON string contained in the incoming ArrayList object. 


Display contents of JSONObject objects 


Returning now to the code in Listing 1 , the next statement calls the display 
method passing the now-populated listC as a parameter. At this point, the 
JSONObject objects stored in listC contain the information that was 
extracted from the JSON strings by the parse method of the JSONValue 
class. 


The display method is shown in its entirety in Listing 3 . 


Note: Listing 3 . The display method. 


static void display(ArrayList input) { 
JSONObject temp = null; 
Iterator<JSONObject> iterator = 
input.iterator(); 
while (iterator.hasNext()){ 
temp = iterator.next(); 
System.out.print("Name: " + 
temp.get("name") ); 
System.out.print(" Age: " + 
temp.get("age")); 
System.out.printiln(" Is student? " + 
temp.get("student")); 
}//end while loop 
}//end display 


This method uses the get method inherited from the HashMap class to get 
and display the values in a list of JSONObject objects for a known set of 
keys. This is plain-vanilla Java code and shouldn't require further 
explanation. The results of this call to the display method are shown in the 
top half of Figure 1. 


Note: Figure 1. Program output. 


Decode using JSONValue class 

Name: Joe Age: 21 Is student? true 

Name: Sue Age: 32 Is student? false 
Name: Tom Age: 19 Is student? true 


Decode using JSONParser class 


Name: Joe Age: 21 Is student? true 
Name: Sue Age: 32 Is student? false 
Name: Tom Age: 19 Is student? true 


The contents of the JSON strings for this same data were displayed in 
Figure 1 of the earlier page titled Json0215: Encoding JSON Strings . 


If you compare the output in the top half of Figure 1 above with the JSON 
string data on the earlier page, you will see that they match. 


Note: 
You could also make the comparison with the data in the code in the early 
portion of Listing 6. 


Decode and display using the JSONParser class 


Returning to the main method, the code in Listing 4 calls the decodeD 
method passing the list of JSON strings along with an empty ArrayList 
object for the purpose of decoding the JSON strings using a parse method 
of the JSONParser class. 


Note: Listing 4 . Decode and display using the JsONParser class. 


//Create another container for decoded JSON 
strings. 

ArrayList <JSONObject> listD = new 
ArrayList<JSONObject>(); 


//Decode and display JSON strings using the 


parse method of the 
// JSONParser class 
System.out.println( "Decode using JSONParser 
class"); 
decodeD(listB, listD); 
display(listD); 
System.out.printin();//blank line 


}//end main 


Then the code in Listing 4 calls the display method to display the results, 
producing the text in the bottom half of Figure 1. 


As you can see, the results in the top and bottom halves of Figure 1 match, 
indicating that both approaches produced the same results. 


The method named decodeD 


The method named decodeD is shown in its entirety in Listing 5 . 


Note: Listing 5 . The method named decodeD. 


static void decodeD(ArrayList input, ArrayList 
output ){ 
JSONParser parser = new JSONParser(); 
String temp = null; 
Iterator<String> iterator = input.iterator(); 
while (iterator.hasNext()){ 
temp = iterator.next(); 


try{ 
//ParseException; must be caught or 


declared to be thrown. 
output.add(parser.parse(temp) ); 
}catch(ParseException pex){ 
pex.printStackTrace(); 
}//end catch 
}//end while loop 
}//end decodeD 


This method decodes a list of JSON strings into JSONObject objects using 
a parse method of the JSONParser class. This code is only slightly more 
complicated than the code shown earlier in Listing 2 that uses a parse 
method of the JSONValue class. 


The additional complexity is due mainly to the fact that the parse method 
throws a checked exception named ParseException . Because it is a 
checked exception, it must either be caught or declared to be thrown by the 
method. I elected to catch it in this program and to simply call the 
printStackTrace method (inherited from the Throwable class) in the catch 
block. However, the ParseException class provides some other methods 
that can be called to elaborate on the nature of the error if desired. 


The end of the program 


Returning to the main method in Listing 4 , there is nothing more to do, so 
the last line in Listing 4 signals the end of the program. 


Run the program 


I encourage you to copy the code from Listing 6. Execute the code and 
confirm that you get the same results as those shown in Figure 1. 
Experiment with the code, making changes, and observing the results of 
your changes. Make certain that you can explain why your changes behave 
as they do. 


Complete program listing 


A complete listing of the program named Code is provided in Listing 6 . 


Note: Listing 6 . The program named Code.java. 


I Ne eR RE Re ek 


KKEKEKKKKKKKEKEKRKKKEKEKEEE 


Copyright 2016 R.G.Baldwin 


OLD CODE: 
Constructs three JSONObject objects and saves them 
in an ArrayList. 
Transforms each JSONObject object into a String 
object and saves the 

strings in a second ArrayList object. 


NEW CODE: 

Decodes the strings into JSONObjects using the 
JSONValue parse method 

and saves them in a third ArrayList object. 
Decodes the strings into JSONObjects using the 
JSONParser class 

and saves them in a fourth ArrayList object. 
Displays both sets of decoded JSON strings. 


Tested with Java 8, Win 7, and json-simple- 
eae, 


KKEKKKRKEKRKKRKRREKR KEKE KEKE RRR KR KERR RRR KEKE RRR KERR KEKE KERR KEKE ESE 


RoR Ee SANE RR he a 


import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 
import org.json.simple.parser.JSONParser; 


import org.json.simple.parser.ParseException; 
import java.util.ArrayList; 
import java.util.Iterator; 


Class Code { 


public static void main(String[] args){ 

//OLD CODE: 

//Create a container for several JSON objects. 

ArrayList <JSONObject> listA = new 
ArrayList<JSONObject>(); 

//Create a container for several JSON strings 

ArrayList <String> listB = new 
ArrayList<String>(); 


//Create and populate the first JSONObject 
with unordered 

// key/value pairs. 

listA.add(new JSONObject()); 

listA.get(0).put("name", "Joe"); 

listA.get(0).put("age", 21); 

listA.get(0).put("student", true); 


//Create and populate the second JSONObject. 
Note that the object 

// 1s populated in a different order than 
above. 

listA.add(new JSONObject()); 

listA.get(1).put("student", false); 

listA.get(1).put("name", "Sue"); 

listA.get(1).put("age", 32); 


//Create and populate the third JSONObject 
listA.add(new JSONObject()); 
listA.get(2).put("name", "Tom"); 
listA.get(2).put("age",19); 


listA.get(2).put("student", true) ; 


//Transform the three JSON objects into JSON 
strings and save 


// them in ListB. Could write them to disk for 


transfer toa 

// different programming environment at this 
point. 

Iterator<JSONObject> iteratorA = 
listA.iterator(); 

while (iteratorA.hasNext()){ 


listB.add(iteratorA.next().toJSONString()); 


}//end while loop 


//NEW CODE BEGINS HERE 


//Create a container for decoded JSON strings. 


ArrayList <JSONObject> listC = new 
ArrayList<JSONObject>(); 


//Decode and display JSON strings using the 
parse method of the 

// JSONValue class 

System.out.printiln( "Decode using JSONValue 
Class"); 

decodeC(listB, listC); 

display(listC); 

System.out.printin();//blank line 


//Create another container for decoded JSON 
strings. 

ArrayList <JSONObject> listD = new 
ArrayList<JSONObject>(); 


//Decode and display JSON strings using the 
parse method of the 
// JSONParser class 


System.out.println( "Decode using JSONParser 
Class"); 

decodeD(listB, listD); 

display(listD); 

System.out.printin();//blank line 


}//end main 
[[------ 7-2-2 rene re rrr er ere eee ee 


//Decode a list of JSON strings into JSONObject 
objects using the 
// parse method of the JSONValue class 
static void decodeC(ArrayList input, ArrayList 
output ){ 
String temp = null; 
Iterator<String> iterator = input.iterator(); 
while (iterator.hasNext()){ 
temp = iterator.next(); 
output .add(JSONValue.parse(temp) ); 
}//end while loop 
}//end decodeC 
[[------ 7-2-2 rr errr re re re er eee eee 


//Decode a list of JSON strings into JSONObject 
objects using the 
// parse method of the JSONParser class 
static void decodeD(ArrayList input, ArrayList 
output ){ 
JSONParser parser = new JSONParser(); 
String temp = null; 
Iterator<String> iterator = input.iterator(); 
while (iterator.hasNext()){ 
temp = iterator.next(); 


try{ 
//ParseException; must be caught or 


declared to be thrown. 
output.add(parser.parse(temp) ); 
}catch(ParseException pex){ 
pex.printStackTrace(); 
}//end catch 
}//end while loop 
}//end decodeD 
[[/---------- 2-2-2 7 ro eer rrr ee -----e 


//Display the values ina list of JSONObject 
objects for a known 
// set of keys. 
static void display(ArrayList input) { 
JSONObject temp = null; 
Iterator<JSONObject> iterator = 
input.iterator(); 
while (iterator.hasNext()){ 
temp = iterator.next(); 
System.out.print("Name: " + 
temp.get("name") ); 
System.out.print(" Age: " + 
temp.get("age")); 
System.out.printiln(" Is student? " + 
temp.get("student")); 
}//end while loop 
}//end display 
[[----------- rr rr errr nr rrr re rere rere ee 


}//end class Code 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


¢ Module name: Json0220: Decoding JSON Strings 
e File: Json0220.htm 
e Published: 05/31/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0220R: Review 

This page contains review questions and answers for the page titled 
"Json0220: Decoding JSON Strings" in the book titled "The json-simple 
Java Library". 


Revised: Sat Jun 04 16:17:01 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


© Question 1 
© Question 2 
© Question 3 
© Question 4 
© Question 5 
© Question 6 
© Question 7 
© Question 8 
© Question 9 
© Question 10 
© Question 11 


e Figure index 
e Listing index 
e Answers 


o Answer 11 
o Answer 10 
o Answer 9 


Answer 8 
Answer 7 
Answer 6 
Answer 5 
Answer 4 
Answer 3 
Answer 2 
Answer 1 


o Oo 0 0 0 0 0 90 


e Figures 
e Listings 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0220: Decoding JSON Strings . Once you 
study that page, you should be able to answer the review questions in this 


page. 


The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 


When a question or an answer provides a link to a figure or a listing, you 
should open that link in a new window to make it easy to view while 
reading the question or the answer. 


Note: 

NOTE: 

With respect to the screen output shown on this page, ignore the possibility 
of output or lack of output similar to the following: 


Note: Code99.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 


Questions 


Question 1. 


True or False? The only way to decode or parse a JSON string with the 
json-simple library is by using the parse method belonging to an object of 
the class named JSONParser . 


Go to answer 1 


Question 2 


True or False? Decoding or parsing a JSON string with the json-simple 
library requires the use of the parse method belonging to either an object of 
the class named JSONParser or an object of the class named JSONValue . 


Go to answer 2 


Question 3 


True or False? The parse method belonging to the class named 
JSONParser can be called without the requirement to instantiate an object 
of the class. 


Go to answer 3 


Question 4 


True or False? The parse methods of the JsONValue and JSONParser 
classes return an object of class JSONString . 


Go to answer 4 


Question 5 


True or False? The code in Listing 1 produces the screen output shown in 
Figure 1 . 


Go to answer 5 


Question 6 


True or False? The code in Listing 2 produces the screen output shown in 
Figure 3 . 


Go to answer 6 


Question 7 


True or False? The code in Listing 3 produces the screen output shown in 
Figure 5 . 


Go to answer 7 


Question 8 


True or False? The code in Listing 4 produces the screen output shown in 
Figure 6 . 


Go to answer 8 


Question 9 


True or False? The code in Listing 5 produces the screen output shown in 
Figure 7 . 


Go to answer 9 


Question 10 


True or False? The code in Listing 6 produces the screen output shown in 
Figure 9 . 


Go to answer 10 


Question 11 


True or False? The code in Listing 7 produces the screen output shown in 
Figure 11. 


Go to answer 11 


Figure index 


« Figure 1 
« Figure 2 
« Figure3 
« Figure 4 
« Figures 
e Figure 6 
« Figure 7 
e Figure 8 


e Figure 9 
e Figure 10 
e Figure 11 


Listing index 


° Listing 1 
° Listing 2 
° Listing 3 
° Listing 4 
° Listing 5 
° Listing 6 
° Listing 7 


What is the meaning of the following two images? 
These images were inserted here simply to insert some space between the 


questions and the answers to keep them from being visible on the screen at 
the same time. 


None L eax] 


Display your name here. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 11 
True. 


Go back to Question 11 


Answer 10 


False. The code in Listing 6 produces the screen output with the errors 
shown in Figure 10. 


Go back to Question 10 


Answer 9 


False. The code in Listing 5 produces the screen output shown in Figure 8 . 
The parse method is not static in the JsONParser class. 


Go back to Question 9 


Answer 8 
True. 


Go back to Question 8 


Answer 7 


True. Even though it is not necessary to instantiate an object of a class to 
call a static method belonging to that class, it is possible to instantiate an 
object of the JSONValue class and to call the static parse method on that 
object. 


Go back to Question 7 


Answer 6 


False. The code in Listing 2 produces the screen output with the compiler 
errors shown in Figure 4. The return value from the parse method must be 
cast from type Object to type JSONObject to store it in a variable of type 
JSONObject . 


Go back to Question 6 


Answer 5 


False. The code in Listing 1 produces the screen output with the compiler 
errors shown in Figure 2. The json-simple library does not define a class 
named JSONString . 


Go back to Question 5 


Answer 4 


False. The json-simple library does not define a class named JSONString . 
Both parse methods return a reference of type java.lang.Object . However, 
it is actually a reference to an object of the class JsONObject , which is a 
subclass of Object several levels down. The reference must be downcast to 
type JSONObject in order to call some of the methods defined in the 
JSONObject class or to store the object's reference in a variable of type 
JSONObject . 


Go back to Question 4 


Answer 3 
False. The parse method belonging to the class named JSONParser is not 
declared static . Therefore, it is an instance method . Instance methods can 


only be called on an object instantiated from the class. 


Go back to Question 3 


Answer 2 
False. The parse method that is defined in the class named JSONValue is a 
static method. Static methods belonging to a class can be called without the 


requirement to instantiate an object of the class. 


Go back to Question 2 


Answer 1 


False. The class named JSONValue also defines a method named parse 
that can be used to decode or parse a JSON string. 


Go back to Question 1 


Figures 


This section contains Figures that may be referred to by one or more 
questions or answers. 


Note: 
Figure 1 


Joe 
21 


Note: 
Figure 2 


Code01.java:8: error: cannot find symbol 
import org.json.simple.JSONString; 
rN 
symbol: class JSONString 
location: package org.json.simple 
Code01.java:20: error: cannot find symbol 
JSONString jsonStringO2 = 
JSONValue. parse(jsonString0101); 
rN 


symbol: class JSONString 
location: class Code01 
Code01.java:20: error: cannot find symbol 


JSONString jsonStringO2 = 
JSONValue. parse(jsonString0101) ; 


symbol: variable jsonString0101 
location: class Code01 
Note: Code01.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 
3 errors 
Error: Could not find or load main class Code01 


Note: 
Figure 3 


Joe 
21 


Note: 
Figure 4 


Code02.java:19: error: incompatible types: Object 
Cannot be converted to JSONObj 
ect 

JSONObject jsonObj02 = 
JSONValue.parse(jsonString); 

rN 

Note: Code02.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 


1 error 
Error: Could not find or load main class Code02 


Note: 
Figure 5 


Joe 
21 


Note: 
Figure 6 


Joe 
21 


Note: 
Figure 7 


Joe 
21 


Note: 
Figure 8 


Code05.java:19: error: non-static method 
parse(String) cannot be referenced from 
a static context 

JSONObject jsonObj02 = 
(JSONObject ) JSONParser.parse(jsonString); 


Note: Code05.java uses unchecked or unsafe 
operations. 

Note: Recompile with -Xlint:unchecked for details. 
1 error 

Error: Could not find or load main class Code05 


Note: 
Figure 9 


Joe 
21 


Note: 
Figure 10 


Code06.java:19: error: unreported exception 
ParseException; must be caught or de 
Cclared to be thrown 

JSONObject jsonObj02 = (JSONObject ) (new 
JSONParser().parse(jsonString) ); 


TAN 
Note: Code06.java uses unchecked or unsafe 


operations. 


Note: Recompile with -Xlint:unchecked for details. 
1 error 


Error: Could not find or load main class Code06 


Note: 
Figure 11 


Joe 
21 


Listings 


This section contains Listings that may be referred to by one or more 
questions or answers. 


Note: 
Listing 1 


PE aegis Shay Dear ae Na ak SP AGP any tenho a eae gas Deh ae te ee 


KRKEKEKKKKKKKEKRKEKEKKKKER 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
alee arlees aleve. 


KRKEKEKKKKKKEKRKRKEKEKEKRKRKEKRE RRR KE KEK KERR KEK RR KEKE KEK KEKE KRKEKRKEKRKEKKEKEEESE 


Rahs City Shady, Reais om A Wat eaten, 


import org.json.simple.JSONObject; 


import org.json.simple.JSONValue; 
import org.json.simple.JSONString; 


Class Code01 { 
public static void main(String[] args){ 


JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "name", "Joe"); 
json0bj01.put( "age", 21); 


String jsonStringO1 = 
json0bj01.toJSONString(); 


JSONString jsonStringO02 = 

JSONValue. parse(jsonString0101) ; 
System.out.println(jsonStringO2.get("name")); 
System.out.println(jsonStringO02.get("age")); 


}//end main 


}//end class Code01 


Note: 
Listing 2 


TION pete Avign sca ate ome he aaa ee gare et ge AY A ghar ga De a dee ha ee mp es ec eat te ae 


KRKEKEKKKKKKKKKEKRKKKKER 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
a Deg Coss bere rt 


KKEKKKKKEKKRKRKRKR KEKE KK KEKE KEK KK KEKE KEKE KK KEKE KEKE KEK KEKE KEKE KKK KKK KKEKEESE 


Radiata te erage oat can teas ates 7. 


import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 


Class Code02 { 
public static void main(String[] args){ 


JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "name", "Joe"); 
json0bj01.put( "age", 21); 


String jsonString = jsonObj01.toJSONString(); 


JSONObject jsonObj02 = 
JSONValue.parse(jsonString); 

System.out.println(json0bj02.get("name") ); 

System.out.printiln(json0Obj02.get("age")); 


}//end main 


}//end class Code02 


Note: 
Listing 3 


TION pete Avign sca ate ome he aaa ee gare et ge AY A ghar ga De a dee ha ee mp es ec eat te ae 


KRKEKEKKKKKKKKKEKRKKKKER 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
a Deg Coss bere rt 


KKEKKKKKEKKRKRKRKR KEKE KK KEKE KEK KK KEKE KEKE KK KEKE KEKE KEK KEKE KEKE KKK KKK KKEKEESE 


Radiata te erage oat can teas ates 7. 


import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 


Class Code03 { 
public static void main(String[] args){ 


JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "name", "Joe"); 
json0bj01.put( "age", 21); 


String jsonString = jsonObj01.toJSONString(); 


JSONObject jsonObj02 = 
(JSONObject ) (new 
JSONValue().parse(jsonString)); 
System.out.println(json0bj02.get("name") ); 
System.out.println(jsonObj02.get("age")); 


}//end main 


}//end class Code03 


Note: 
Listing 4 


eB PAPI R ee nnn et Sarena On Dee at Re ee Regge ee ear ES Aig ae ete Gs Rare Rear pee Meee ee atc te 


KRKEKEKKKKKKKEKKEKEKKEKKER 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
alee Cb a Legler 


KKEKKKKKKKRKRKREKRKRKR KERR KEKE KKK KEKE KERR KEKE KEKE KEKE KKK KKK KEKEKEEKSE 


ea Sa Pic rage ARE dl Ruan ee say f 


import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 


Class Code04 { 
public static void main(String[] args){ 


JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "name", "Joe"); 
json0bj01.put( "age", 21); 


String jsonString = jsonObj01.toJSONString(); 


JSONObject jsonObj02 = 
(JSONObject ) JSONValue.parse(jsonString); 

System.out.println(json0bj02.get("name") ); 

System.out.println(jsonObj02.get("age")); 


}//end main 


}//end class Code04 


Note: 
Listing 5 


SS AiR Ea Sibel avcd SCrea ca ses Sa Bs Eras er CaS al Aa a en SA Za Sar See aa aie Wa a Aa 


KRKEKEKKKKKKKEKKEKEKKEKKER 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
alee Cb a Legler 


KKEKKKKKKKRKRKREKRKRKR KERR KEKE KKK KEKE KERR KEKE KEKE KEKE KKK KKK KEKEKEEKSE 


ea Sa Pic rage ARE dl Ruan ee say f 


import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 


Class CodeO05 { 
public static void main(String[] args){ 


JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "name", "Joe"); 
json0bj01.put( "age", 21); 


String jsonString = jsonObj01.toJSONString(); 


JSONObject jsonObj02 = 
(JSONObject ) JSONParser.parse(jsonString); 

System.out.println(json0bj02.get("name") ); 

System.out.println(json0Obj02.get("age")); 


}//end main 


}//end class Code05 


Note: 
Listing 6 


YES EAE Ea ibe avon Crea ca ses Sa Bist ras ger CaS al AA de aS A Za Sar Se aaa a aA a 


KRKEKEKKKKKKKEKKEKEKKEKKER 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
alee Cb a Legler 


KKEKKKKKKKRKRKREKRKRKR KERR KEKE KKK KEKE KERR KEKE KEKE KEKE KKK KKK KEKEKEEKSE 


Nahata re te nea aera 


import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 


Class Code0dé { 
public static void main(String[] args){ 


JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "name", "Joe"); 
jJson0bj01.put( "age", 21); 


String jsonString = jsonObj01.toJSONString(); 


JSONObject jsonObj02 = 
(JSONObject ) (new 
JSONParser().parse(jsonString) ); 
System.out.println(json0bj02.get("name") ); 
System.out.println(json0Obj02.get("age")); 


}//end main 


}//end class Code06 


Note: 
Listing 7 


a RE Aoi Sena Meta cameo ae Pe aadeaag cin Ag Cea Sa te har dea eRe tae pest ee 


KKEKKKKKKKRKRKEKRKKEKKKEKSE 


Copyright 2016 R.G.Baldwin 
Tested with Java 8, Win 7, and json-simple- 
a Dea Cs baby Ie Wee 


KRKEKEKKKKKRKRKRKRKRKRKEKEKRKRKRE KERR KE KER KERR KE KERR KERR KKK KKK KRKRKKEKEKEEKESE 


pei ae aR iia casa adh tenis eae oa 4 


import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 


Class Code07 { 


public static void main(String[] args) throws 
ParseException{ 


JSONObject jsonObjO1 = new JSONObject(); 
json0bj01.put( "name", "Joe" ); 
json0bj01.put( "age", 21); 

String jsonString = jsonObj01.toJSONString(); 


JSONObject jsonObj02 = 
(JSONObject ) (new 


JSONParser().parse(jsonString) ); 
System.out.println(jsonObj02.get("name") ); 
System.out.println(jsonObj02.get("age")); 

}//end main 


}//end class Code07 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0220R: Review 
e File: Json0220R.htm 
e Published: 06/04/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0225: Encoding JSON Arrays 

Learn how to encode JSON array data using the JsSONArray class. Also 
learn how to write an encoded JSON string to an output text file for 
transport to a different computing environment. 


Revised: Thu Jun 02 19:27:08 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


e Table of contents 
e Preface 


o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


Beginning of the class and the main method 


Create and populate another similar JSON object 
Put the players in the game 

Write the JSON string to an output file 

The end of the program 

The contents of the output file 

Decoded output data 


oOo 0 0 0 0 0 0 *O 


e Run the program 
¢ Complete program listing 


e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page explains how to encode JSON 
array data using the JSONArray class. It also shows how to write an 
encoded JSON string to an output text file for transport to a different 
programming environment. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Prettified version of output file contents. 
e Figure 2. Beginning of output file contents. 
e Figure 3. Decoded output data. 


Listings 


e Listing 1. Beginning of the class and the main method. 

e Listing 2. Instantiate and populate a JSONArray object. 

e Listing 3. Populate hashMapA. 

e Listing 4. Create and populate another similar JSON object. 
e Listing 5. Put the players in the game. 

e Listing 6. Write the JSON string to an output file. 

e Listing 7. The program named Code.java. 


General background information 


As you leamed in the page titled Json0210: Structure of the json-simple 
Java Library_, the JSONArray class extends the standard Java ArrayList 
class. Once you have an object of the JSONArray class, you have access to 
all of the methods defined in and inherited into the JsONArray class. 


The sample program that follows will use the JSONArray class to 
construct a JSON string containing nested arrays and will then write the 
string to an output file suitable for transport to a different programming 
environment. 


A later page in this book will read the JSON string from the file and decode 
it into its component parts. 


Discussion and sample code 


The program named Code (see Listing 7) creates a JSON string and writes 
it to an output file. The json string contains an array, which in turn contains 
two nested arrays. 


Beginning of the class and the main method 


I will discuss and explain the program in fragments. The first fragment is 
shown in Listing 1. 


Note: Listing 1 . Beginning of the class and the main method. 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import java.io.PrintwWriter; 

import java.io.File; 

import java.io.IOException; 


Class Code{ 


public static void main(String[] args) { 
//Create a json object. which is a subclass 
// of the Java HashMap class. 
JSONObject hashMapA = new JSONObject(); 


//Populate the json object with a key/value 
// pair. 
hashMapA.put("name", "Tom" ); 


There is nothing new in Listing 1 so that code shouldn't require further 
explanation. Note however, that the name "Tom" will become significant in 
a later discussion. 


Instantiate and populate a JSONArray object 


The code in Listing 2 instantiates and populates a JSONArray object. 


Note: Listing 2 . Instantiate and populate a JSONArray object. 


JSONArray arrayListA = new JSONArray(); 
arrayListA.add("2-club"); 
arrayListA.add("3-heart"); 
arrayListA.add("4-diamond"); 
arrayListA.add("5-spade"); 


Previous pages in this book have constructed JSON strings using a subclass 
of the Java HashMap class -- (the JsONObject class) . It is worth noting 
that JSON strings constructed in that manner are unordered. However, 
JSON arrays constructed using the JSONArray class, which is a subclass 
of the ArrayList class, are ordered lists. 


The program that I will explain in this page is intended to represent the 
beginning state of a two-person card game where each player receives four 
cards. The code in Listing 2 constructs a list of the cards that will be dealt to 
one of the players. 


Populate hashMapA with a key/value pair 


The code in Listing 3 populates the JsONObject object referred to as 
hashMapA with a key/value pair where the key is "cards" and the value is 
an object of the JSONArray class containing a list of strings naming 
specific playing cards. 


Note: Listing 3 . Populate hashMapA. 


hashMapA.put("cards",arrayListA); 


Note that hashMapA already contained a key/value pair identifying one of 
the players in the game named "Tom" (see Listing_1_). Thus the code in 
Listing 1 through Listing 3 can be though of as "dealing" the cards 
identified in Listing 2 to the player named "Tom". 


Create and populate another similar JSON object 


Listing 4 creates and populates a second list of playing cards and deals them 
to the second player in the game whose name is "Joe". 


Note: Listing 4 . Create and populate another similar JSON object. 


JSONObject hashMapB = new JSONObject(); 
hashMapB.put("name", "Joe"); 


JSONArray arrayListB = new JSONArray(); 
arrayListB.add("4-heart"); 
arrayListB.add("5-heart"); 
arrayListB.add("6-club"); 
arrayListB.add("7-diamond" ); 
hashMapB.put("cards",arrayListB); 


Put the players in the game 


Now that the players have been created and have received their cards, it is 
time to put them in the game. 


Listing 5 begins by adding the two players and their card arrays to a new 
object of type JSONArray . This results in nested arrays. 


Note: Listing 5 . Put the players in the game. 


JSONArray arrayListC = new JSONArray(); 
arrayListC.add(hashMapA) ; 
arrayListC.add(hashMapB) ; 


JSONObject hashMapC = new JSONObject(); 
hashMapC.put("game", arrayListC); 


Then Listing 5 creates anew JSONObject object to represent the game and 
populates it with a key/value pair where the key is "game" and the value is 
the array containing the two players and their card arrays. 


Write the JSON string to an output file 


Listing 6 calls the writeJSONString method on the JSONObject object to 
encode the object into a JSON string and write it to an output file named 
junk.json . 


Note: Listing 6 . Write the JSON string to an output file. 


try{ 
Printwriter out = 


new PrintWriter(new File("junk.json")); 
hashMapC.writeJSONString(out); 
out.flush(); 
}catch(IOException ex){ 
ex.printStackTrace(); 
}//end catch 


}//end main 


}//end class Code 


Note that the output file is simply a text file with the extension .json . Thus 
it can be read by any program that is capable of reading plain text files. 


The end of the program 


Listing 6 also signals the end of the main method and the end of the 
program. 


The contents of the output file 


Figure 1 shows a "prettified" version of the contents of the output file. 


Note: Figure 1. Prettified version of output file contents. 


{"game": 
[ 
"cards": 
"2-club","3-heart","4-diamond", "5-spade" 
1, 
"name":"Tom" 
}, 
{ 
“Cards”: 
"A-heart", "5-heart", "6-club","7-diamond" 
1, 
"name":"Joe" 
} 


The actual contents of the file do not contain line breaks and indentation as 
shown in Figure 1. Those cosmetic features were added manually to Figure 
1 to make it easier for you to correlate the output with the code shown 
earlier. Instead, the actual file consists simply of a string of characters that 
begins as shown in Figure 2. 


Note: Figure 2. Beginning of output file contents. 


{"game": [{"cards":["2-club", "3-heart", "4- 
diamond","5-spade"],... 


Decoded output data 


As mentioned earlier, a later page in this book will read the JSON string 
from the file and decode it into its component parts. Figure 3 shows a 
preview of what you will see on that page. 


Note: Figure 3. Decoded output data. 


First Player's Name: Tom 
First Player's cards 
2-club 

3-heart 

4-diamond 

5-spade 


Second Player's Name: Joe 
Second Player's cards 
4-heart 

5-heart 

6-club 

7-diamond 


Figure 3 shows the JSON string decoded and formatted into a display that is 
representative of the intent of the string -- to encapsulate information about 
the players and their cards in a game of cards. 


Run the program 
I encourage you to copy the code from Listing 7. Execute the code and 
confirm that your output file matches that shown in Figure 2.. Experiment 


with the code, making changes, and observing the results of your changes. 
Make certain that you can explain why your changes behave as they do. 


Complete program listing 


Listing 7 provides a complete listing of the program named Code.java . 


Note: Listing 7 . The program named Code.java. 


Pe Pe TO ART OM ea ete ter who Sako DA hata tet ibe ®: Rohtak hehehe chk koe 


Copyright: R.G.Baldwin 2016 
Revised: 06/01/16 


Creates a json string and writes it to an output 
file. The json string contains an array, which in 
turn contains two arrays. 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


SP SAGAS Arte IRA I ARC aE Re BOG RY ARE GARIN GE Gai Soa a IR acs Hedge 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import java.io.Printwriter; 

import java.io.File; 

import java.io.IOException; 


Class Code{ 


public static void main(String[] args){ 
//Create a json object. which is a subclass 
// of the Java HashMap class. 
JSONObject hashMapA = new JSONObject(); 


//Populate the json object with a key/value 
// pair. 
hashMapA.put("name", "Tom" ); 


//Create and populate a json array, which is 
// a subclass of the Java ArrayList class. 
JSONArray arrayListA = new JSONArray(); 
arrayListA.add("2-club"); 
arrayListA.add("3-heart"); 
arrayListA.add("4-diamond" ); 
arrayListA.add("5-spade"); 


//Populate the json object with a key/value 
// pair where the value is an array. 
hashMapA.put("cards",arrayListA); 


//Create and populate another similar json 
// object. 
JSONObject hashMapB = new JSONObject(); 


hashMapB.put("name", "Joe"); 


JSONArray arrayListB = new JSONArray(); 
arrayListB.add("4-heart"); 
arrayListB.add("5-heart"); 
arrayListB.add("6-club"); 
arrayListB.add("7-diamond" ); 
hashMapB.put("cards",arrayListB); 


//Create another json array and populate 
// it with the two json objects created 
// earlier. 

JSONArray arrayListC = new JSONArray(); 
arrayListC.add(hashMapA) ; 
arrayListC.add(hashMapB) ; 


//Create another json object and populate 
// it with a key/value pair where the value 
// is the array from above. 

JSONObject hashMapC = new JSONObject(); 
hashMapC.put("game",arrayListC); 


try{ 
//Encode the HashMap object into a 


// json String and write it to an output 
// file. Note that it is simply a text file 
// with a different extension. 
PrintWriter out = 
new PrintWriter(new File("junk.json")); 
hashMapC.writeJSONString(out); 
out.flush(); 
}catch(IOException ex){ 
ex.printStackTrace(); 
}//end catch 


}//end main 


}//end class Code 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0225: Encoding JSON Arrays 
e File: Json0225.htm 
e Published: 06/01/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : | am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0225R: Review 

This page contains review questions and answers for the page titled 
"Json0225: Encoding JSON Arrays" in the book titled "The json-simple 
Java Library". 


Revised: Sun Jun 05 10:59:02 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


© Question 1 
© Question 2 
© Question 3 
© Question 4 
© Question 5 
© Question 6 
© Question 7 


e Figure index 
e Listing index 
e Answers 


Answer 7 
Answer 6 
Answer 5 
Answer 4 
Answer 3 
Answer 2 
Answer 1 


o Oo 0 0 0 0 90 


e Figures 
e Listings 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0225: Encoding JSON Arrays . Once you 
study that page, you should be able to answer the review questions in this 


page. 


The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 


When a question or an answer provides a link to a figure or a listing, you 
should open that link in a new window to make it easy to view while 
reading the question or the answer. 


Note: 

NOTE: 

With respect to the screen output shown on this page, ignore the presence 
or absence of output similar to the following: 


Note: Code99.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 


Questions 


Question 1. 


True or False? The JSONArray class extends the standard Java HashMap 
class. 


Go to answer 1 


Question 2 


True or False? The JSONArray class represents a true Java array. The 
elements in a JSONArray object can be accessed using the square bracket 
([]) notation commonly associated with Java arrays. 


Go to answer 2 


Question 3 


True or False? The code in Listing 1 produces the screen output shown in 
Figure 1 . 


Go to answer 3 


Question 4 


True or False? The code in Listing 2 produces the screen output shown in 
Figure 3 . 


Go to answer 4 


Question 5 


True or False? The code in Listing 3 produces the screen output shown in 
Figure 5. 


Go to answer 5 


Question 6 


True or False? The code in Listing 4 produces the screen output shown in 
Figure 6. 


Go to answer 6 


Question 7 


True or False? The code in Listing 5 produces the screen output shown in 
Figure 8 . 


Go to answer 7 


Figure index 


° [igure 1 
° Figure 2 
e Figure 3 
° Figure 4 
* Figure 5 
+ Figure.6 
* Figure 7 
e Figure 8 


Listing index 


° Listing 1 
e Listing 2 


e Listing 3 
e Listing 4 
e Listing 5 


What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


None Cox) 


Display your nameshere, 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 
Put your name here 


Answers 


Answer 7 


True. As a subclass of the ArrayList class, an object of the JsONArray 
class allows duplicate elements. 


Go back to Question 7 


Answer 6 


False. The code in Listing 4 produces the screen output shown in Figure 7 . 


Go back to Question 6 


Answer 5 


True. The JSONArray class provides two overloaded versions of the 
method named toJSONString . One is an instance method and the other is 


a static method. On a side note, this is also true of the class named 
JSONObject . 


Go back to Question 5 


Answer 4 


False. The code in Listing 2 produces the screen output shown in Figure 4 . 
Unlike an object of the JSONObject class, an object of the JSONArray 
class is an ordered list. By this we mean that the user has precise control 
over where in the list each element is inserted. The user can access elements 
by their integer index (position in the list) . 


Go back to Question 4 


Answer 3 


False. The code in Listing 1 produces the screen output with the errors 
shown in Figure 2. The JSONArray class neither defines nor inherits a 
method named put . 


Go back to Question 3 


Answer 2 


False. The JSONArray class extends the ArrayList class, which 
implements the List interface. Therefore, an object of the JsONArray 
class is a list and is not an array. For example, the elements in a 
JSONArray object cannot be accessed using the square bracket ([]) 
notation commonly associated with Java arrays. Instead, the elements are 
accessed using the add and get methods declared in the List interface and 
inherited from the ArrayList class. 


Go back to Question 2 


Answer 1 
False. The JSONArray class extends the standard Java ArrayList class. 


Go _ back to Question 1 


Figures 


This section contains Figures that may be referred to by one or more 
questions or answers. 


Note: 
Figure 1 


[{"Name":"Tom"}, {"Age":21}, {"Student": true} ] 


Note: 
Figure 2 


Code01.java:22: error: cannot find symbol 
array.put(json0bj01); 
AN 


symbol: method put(JSONObject) 

location: variable array of type JSONArray 
Code01.java:23: error: cannot find symbol 
array.put(json0Obj02); 

rN 


symbol: method put(JSONObject) 

location: variable array of type JSONArray 
Code01.java:24: error: cannot find symbol 
array.put(json0bj03) ; 

rN 


symbol: method put(JSONObject) 

location: variable array of type JSONArray 
Note: Code01.java uses unchecked or unsafe 
operations. 

Note: Recompile with -Xlint:unchecked for details. 
3 errors 

Error: Could not find or load main class Code01 
Press any key to continue 


Note: 
Figure 3 


[{"Name":"Tom"}, {"Age":21}, {"Student": true} ] 
Note: 

Figure 4 
[{"Name":"Tom"}, {"Student": true}, {"Age":21} ] 


Note: 
Figure 5 


[{"Name":"Tom"}, {"Age":21}, {"Student":true}] 
[{"Name":"Tom"}, {"Age":21}, {"Student": true} ] 


Note: 
Figure 6 


{"person":[{"Student":true}, {"Age":21}, 
{"Name":"Tom"}]} 


Note: 
Figure 7 


[{"Student":true}, {"Age":21}, {"Name":"Tom"} ] 


Note: 
Figure 8 


{"person":[{"Name":"Tom"}, {"Age":21}, 
{"Name":"Tom"} ]} 


Listings 


This section contains Listings that may be referred to by one or more 
questions or answers. 


Note: 
Listing 1 


fois BAIR OR NIRA hath eae abn titan Saguie, WERE ERY ede Mot Ran uate On Moneta ata on ody Nr 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


PN Range hah ROR aie AN Ma eon ta am aha eteeN, ate awe © he Na yn thc Me teet ern Raat Na 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 


Class Code01{ 


public static void main(String[] args){ 
JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bjO3.put( "Student", true); 


JSONArray array = new JSONArray(); 
array.put(json0bj01); 
array.put(json0bj02); 
array.put(json0bj03); 
System.out.printiln(array.toJSONString()); 


}//end main 


}//end class Code01 


Note: 
Listing 2 


TOR RR LG REIL ROAR RN OR Masa te cae ae te aN tea Waid aman ae eee IM a te Micah, Oe 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


NRO N I sith Meade Minty amet ea ach ete hate Wat ain Aer ats Mate ny Wome Naty teeny aane oe eke Nef 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 


Class Code02{ 


public static void main(String[] args){ 
JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray array = new JSONArray(); 
array.add(0, jsonObj01); 

array.add(1, json0Obj03); 

array.add(2, jsonObj02); 
System.out.println(array.toJSONString()); 


}//end main 


}//end class Code02 


Note: 
Listing 3 


TOR RR LG REIL ROAR RN OR Masa te cae ae te aN tea Waid aman ae eee IM a te Micah, Oe 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


NRO N I sith Meade Minty amet ea ach ete hate Wat ain Aer ats Mate ny Wome Naty teeny aane oe eke Nef 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 


Class Code03{ 


public static void main(String[] args){ 
JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0Obj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray array = new JSONArray(); 
array.add(json0bj01); 
array.add(json0bj02); 
array.add(json0bj03); 


System.out.println(JSONArray.toJSONString(array) ); 
System.out.println(array.toJSONString()); 


}//end main 


}//end class Code03 


Note: 
Listing 4 


oT OR LAER ARMA Ke tea Rago fret e TaN, Wate Me Wants Wan grag ym Mase ay ate Miah ce 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


Si RA eA ss Rey Re Naser AE RAs Retin AN Sy Aes eS BS Ta Sat Rea gr eg Reece 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 


Class Code04{ 


public static void main(String[] args){ 
JSONObject jsonObj0O1 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray array = new JSONArray(); 
array.add(json0bj03) ; 
array.add(json0bj02); 
array.add(json0bj01); 


JSONObject jsonObj04 = new JSONObject(); 
json0bj04.put("person",array); 


System.out.println(array.toJSONString()); 
}//end main 


}//end class Code04 


Note: 
Listing 5 


FA ESE SAS ESAS SAU Aa AES Ia ESET SR RS RSS RA sg a i nan Seca a GR A TEE A ST a 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


Se RAC OSS Re Sai Ree SRI AE SSA Retin AN es Sy Me Siic se ao Sa ToS Seah eR eg Ress ay 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 


Class Code05{ 


public static void main(String[] args){ 
JSONObject jsonObjO1 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray array = new JSONArray(); 


array.add(json0bj01) ; 
array.add(json0bj02); 
array.add(json0bj01) ; 


JSONObject jsonObj04 = new JSONObject(); 
json0bj04.put("person",array); 


System.out.println(json0bj04.toJSONString()); 
}//end main 


}//end class Code05 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0225R: Review 
e File: Json0225R.htm 
e Published: 06/05/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 


I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0230: Decoding JSON Arrays 
Learn how to read a JSON string containing nested array data from a file, 
decode it, and display its component parts. 


Revised: Thu Jun 02 19:28:45 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library.. 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of contents 


Table of contents 
Preface 


o Viewing tip 


=» Figures 
= Listings 


e General background information 
e Discussion and sample code 


Read the file containing the JSON string 
Display the JSON string 

Access the game array 

Get information about the first player 


The end of the program 


oOo 0 0 0 0 O 


e Run the program 
¢ Complete program listing 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page explains how to read a JSON 
string containing nested array data from a file, decode it, and display its 
component parts. 


Viewing tip 


I recommend that you open another copy of this module in a separate 
browser window and use the following links to easily find and view the 
Figures and Listings while you are reading about them. 


Figures 


e Figure 1. Screen shot of raw JSON string. 

e Figure 2 . Display first player's name. 

e Figure 3. The first player's cards. 

e Figure 4. Information about the second player. 


Listings 


e Listing 1. Read the file containing the JSON string. 

e Listing 2.. Display the JSON string. 

e Listing 3. Access the game array. 

e Listing 4. Get information about the first player. 

e Listing 5. Display first player's cards. 

e Listing 6. Get and display information about the second player. 
e Listing 7. The program named Code.java. 


General background information 


You learned how to encode JSON data containing nested arrays and how to 
write the encoded JSON string to an output file in the page titled Json0225: 
Encoding JSON Arrays . The program that I will discuss and explain in the 
next section will read that file from the disk, decode it, and display its 
component parts. 


Discussion and sample code 


The program named Code (see Listing_7_) reads and parses an input file 
named junk.json , The file contains a JSON string with nested array data. 


Read the file containing the JSON string 


I will discuss and explain this program in fragments. The first fragment is 
shown in Listing 1. 


Note: Listing 1 . Read the file containing the JSON string. 


Class Code{ 


public static void main(String[] args) { 
//Instantiate a JSONObject object, which is a 
subclass of the 
// Java HashMap class. 
JSONObject jsonMap = null; 
cial 
//Read json string from a file and parse it 
into a HashMap. 
jsonMap = 
(JSONObject ) (JSONValue. parse(new 
FileReader("junk.json"))); 
}catch(IOException ex){ 


ex.printStackTrace(); 
}7//end catch 


The code in Listing 1 shows the beginning of the class and the beginning of 
the main method. This code reads the JSON string from the input file 
named junk.json and parses the data into an object of type JsONObject . 


There is nothing new in Listing 1 so the code shouldn't need further 
explanation. When the code in Listing 1 has finished executing, all of the 
information from the JSON string in the file is encapsulated in the object of 
type JSONObject referred to as jsonMap . 


Display the JSON string 


The code in Listing 2 displays the raw JSON string followed by a blank 
line. 


Note: Listing 2 . Display the JSON string. 


System.out.println("json string: " + jsonMap); 
System.out.printlin();//blank line 


This code produces the screen output shown by the screen shot in Figure 1. 


Note: Figure 1. Screen shot of raw JSON string. 


json string: {"game":[{"cards":["2-club","3- 
heart", "4-diamond","5-spade"], "name" 

-"Tom"}, {"cards":["4-heart", "5-heart", "6-club","7- 
diamond"],"name":"Joe"}]} 


Note that the line break in Figure 1 was inserted by the operating system 
while displaying the string in the command-line window. The line break 
does not exist in the data in the file. 


Access the game array 


Listing 3 calls the get method inherited from the HashMap class to get the 
game array into an object of type JSONArray , which is a subclass of the 
ArrayList class. 


Note: Listing 3 . Access the game array. 


JSONArray gameArrayList = 
(JSONArray )jsonMap.get("game"); 


Get information about the first player 


Recall that a JSONArray object is an ordered list as a subclass of the 
ArrayList class. The get method inherited from the ArrayList class can be 
used to access elements in the list on the basis of a zero-based index. At this 
point, information about the first player is stored in the list as an object of 


type JSONObject . (It is actually stored as type Object and must be 
downcast to type JSONObject in order to do much with it.) 


Listing 4 begins by accessing the element at an index value of zero, which 
is the object containing information about the first player. 


Note: Listing 4 . Get information about the first player. 


JSONObject firstPlayerMap = 
(JSONObject)gameArrayList.get(0O); 
System.out.printin("First Player's Name: " + 


firstPlayerMap.get("name") ); 


Then Listing 4 uses the get method inherited from the HashMap class to 
get and display the value associated with the key "name". This produces the 
screen output shown in Figure 2 . 


Note: Figure 2. Display first player's name. 


First Player's Name: Tom 


Display first player's cards 


Listing 5 begins by using the get method of the HashMap class to access 
the JSONArray object that is the value for the key "cards". 


Note: Listing 5 . Display first player's cards. 


JSONArray firstPlayerCardsList = 
(JSONArray)firstPlayerMap.get("cards"); 
System.out.printiln("First Player's cards"); 


Iterator<String> iterator = 
firstPlayerCardsList.iterator(); 
while (iterator.hasNext()) { 
System.out.printiln(iterator.next()); 
}//end while loop 


Then Listing 5 uses an iterator to iterate through the JSONArray object 
and to display each of the cards in the array, (which is actually a list at this 
point) . This code produces the output shown in Figure 3 . 


Note: Figure 3. The first player's cards. 


First Player's cards 
2-club 

3-heart 

4-diamond 

5-spade 


Get and display information about the second player 


Listing 6 uses similar code to get and display information about the second 
player. 


Note: Listing 6 . Get and display information about the second player. 


System.out.printin(); 
JSONObject secondPlayerMap = 

(JSONObject )gameArrayList.get(1); 
System.out.println("Second Player's Name: " + 


secondPlayerMap.get("name") ); 
JSONArray secondPlayerCardsList = 

(JSONArray )secondPlayerMap.get("cards"); 
System.out.println("Second Player's cards"); 
iterator = secondPlayerCardsList.iterator(); 
while (iterator.hasNext()) { 

System.out.printiln(iterator.next()); 
}//end while loop 
}//end main 


}//end class Code 


This code produces the screen output shown in Figure 4 . 


Note: Figure 4. Information about the second player. 


Second Player's Name: Joe 
Second Player's cards 
4-heart 

5-heart 

6-club 

7-diamond 


The end of the program 


Listing 6 signals the end of the main method and the end of the program. 


Run the program 


Click here to download a zip file containing a JSON data file named 
junk.json that can be used to experiment with this program. 


I encourage you to copy the code from Listing 7. Execute the code and 
confirm that you get the same results as those shown in Figure 1 through 
Figure 4. Experiment with the code, making changes, and observing the 
results of your changes. Make certain that you can explain why your 
changes behave as they do. 


Complete program listing 


A complete listing of the program named Code is provided in Listing 7 . 


Note: Listing 7 . The program named Code.java. 


ee ee ROR ha RR ee te ee ee a ee 


KEKE KKKKKRKRKKKEKEKEKEKEKER 


Copyright: R.G.Baldwin 2016 
Revised: 06/01/16 


Reads a json string from a file, parses, and 
displays some of its parts. 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


KKEKKKRKKRKKRKRKRKR KEK KRKR KEKE KEK RRR KERR KK KEKE KEKE KKK KEKE KKK KE 


PUMA SORE ROR SR Son A aie ere hay 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONValue; 
import java.io.IOException; 

import java.io.FileReader; 

import java.util.*; 


Class Code{ 


public static void main(String[] args) { 
//Instantiate a JSONObject object, which is a 
subclass of the 
// Java HashMap class. 
JSONObject jsonMap = null; 
try{ 
//Read json string from a file and parse it 
into a HashMap. 
jsonMap = 
(JSONObject ) (JSONValue. parse(new 
FileReader("junk.json"))); 
}catch(IOException ex){ 
ex.printStackTrace(); 
}//end catch 


//Get and display the json string 
System.out.println("json string: " + jsonMap); 


System.out.printin();//blank line 


//Get the game array into an ArrayList object. 
JSONArray gameArrayList = 
(JSONArray )jsonMap.get("game"); 


//Get and display info about the first player. 
JSONObject firstPlayerMap = 

(JSONObject )gameArrayList.get(0); 
System.out.printin("First Player's Name: " + 


firstPlayerMap.get("name") ); 
JSONArray firstPlayerCardsList = 


(JSONArray)firstPlayerMap.get("cards"); 
System.out.printiln("First Player's cards"); 
Iterator<String> iterator = 

firstPlayerCardsList.iterator(); 
while (iterator.hasNext()) { 

System.out.printin(iterator.next()); 
}//end while loop 


//Get and display info about the second 
player. 
System.out.printin(); 
JSONObject secondPlayerMap = 
(JSONObject )gameArrayList.get(1); 
System.out.println("Second Player's Name: " + 


secondPlayerMap.get("name") ); 
JSONArray secondPlayerCardsList = 
(JSONArray )secondPlayerMap.get("cards"); 


System.out.println("Second Player's cards"); 
iterator = secondPlayerCardsList.iterator(); 


while (iterator.hasNext()) { 
System.out.println(iterator.next()); 
}//end while loop 


}//end main 


}//end class Code 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0230: Decoding JSON Arrays 
e File: Json0230.htm 
e Published: 06/01/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 


nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Json0230R: Review 

This page contains review questions and answers for the page titled 
"Json0230: Decoding JSON Arrays" in the book titled "The json-simple 
Java Library". 


Revised: Tue Jun 07 10:33:04 CDT 2016 
This page is included in the following Books: 
e The json-simple Java Library . 


e INEW2338 - Advanced Java Programming 
e Object-Oriented Programming (OOP) with Java 


Table of Contents 


e Table of Contents 
e Preface 
e Questions 


© Question 1 
© Question 2 
© Question 3 
© Question 4 


e Figure index 
e Listing index 
e Answers 


o Answer 4 
o Answer 3 
o Answer 2 
o Answer 1 


e Figures 
e Listings 
e Miscellaneous 


Preface 


This is a page from the book titled The json-simple Java Library . The 
book explains how to use the json-simple Java library to generate, 
transform, and query JSON text. This page provides review questions and 
answers for the page titled Json0230: Decoding JSON Arrays . Once you 
study that page, you should be able to answer the review questions in this 


page. 


The questions and the answers in this page are connected by hyperlinks to 
make it easy for you to navigate from the question to the answer and back 
again. 


When a question or an answer provides a link to a figure or a listing, you 
should open that link in a new window to make it easy to view while 
reading the question or the answer. 


Note: 

NOTE: 

With respect to the screen output shown on this page, ignore the presence 
or absence of output similar to the following: 


Note: Code99.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 


Questions 


Question 1. 


True or False? The code in Listing 1 produces the screen output shown in 
Figure 1 . 


Go to answer 1 


Question 2 


True or False? The code in Listing 2 produces the screen output shown in 
Figure 3 . 


Go to answer 2 


Question 3 


True or False? The code in Listing 3 produces the screen output shown in 
Figure 5. 


Go to answer 3 


Question 4 


True or False? The code in Listing 4 produces the screen output shown in 
Figure 7 . 


Go to answer 4 


Figure index 


* Figure 1 
« Figure 2 
« Figure.3 
« Figure 4 
« Figures 
e Figure 6 
e Figure 7 


Listing index 


° Listing 1 
° Listing 2 
° Listing 3 
° Listing 4 


What is the meaning of the following two images? 


These images were inserted here simply to insert some space between the 
questions and the answers to keep them from being visible on the screen at 
the same time. 


Ey None . eles 
Display your nameshiere. 


This image was also inserted for the purpose of inserting space between the 
questions and the answers. 


Prob05a.jpg 


Put your name here 


Answers 


Answer 4 
True. 


Go back to Question 4 


Answer 3 


False. The code in Listing 3 produces the screen output with the error 
shown in Figure 6 . 


Go back to Question 3 


Answer 2 


False. The code in Listing 2 produces the screen output with the error 
shown in Figure 4 . 


Go back to Question 2 


Answer 1 


False. The code in Listing 1 produces the screen output with the error 
shown in Figure 2 . 


Go back to Question 1 


Figures 


This section contains Figures that may be referred to by one or more 
questions or answers. 


Note: 
Figure 1 


Tom 


Note: 
Figure 2 


Code01.java:36: error: incompatible types: Object 
Cannot be converted to String 
String temp02 = temp01.get("Name"); 
rN 
Note: Code01.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 


1 error 
Error: Could not find or load main class Code01 


Note: 
Figure 3 


Tom 
21 


Note: 
Figure 4 


Code02.java:40: error: incompatible types: String 
Cannot be converted to Long 
Long temp04 = (String)(temp03.get("Age")); 
rN 


Note: Code02.java uses unchecked or unsafe 
operations. 

Note: Recompile with -Xlint:unchecked for details. 
1 error 

Error: Could not find or load main class Code02 


Note: 
Figure 5 


Tom 


2a 
true 


Note: 
Figure 6 


Code03.java:44: error: incompatible types: String 
Cannot be converted to Boolean 


Boolean temp06 = (String) 

(temp05.get("Student")); 
rN 

Note: Code03.java uses unchecked or unsafe 
operations. 
Note: Recompile with -Xlint:unchecked for details. 
1 error 
Error: Could not find or load main class Code03 


Note: 
Figure 7 


Tom 
21 
true 


Listings 


This section contains Listings that may be referred to by one or more 
questions or answers. 


Note: 
Listing 1 


fon BARON IIIA hath ese abn thine Saguie, WERE ER aad Mot Ran yates ean ata on oe net 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 
KKEKEKKKKKRKEKRKEKRKEKRKE KEKE KR KEKE KEKE KERR KKK KEKE KEKE KEKE KEKE KER KEKE KKK KEKE EEK 


ERR RON RE WN te Way hapa, 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONValue; 


Class Code01{ 


public static void main(String[] args){ 
JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray arrayO1 = new JSONArray(); 
arrayO1.add(jsonObj01); 
arrayO1.add(json0Obj02); 
array0O1.add(json0bj03); 


JSONObject jsonObj04 = new JSONObject(); 


json0bj04.put("person",arrayO1); 
String jsonString = json0Obj04.toJSONString(); 


JSONObject jsonObj05 = (JSONObject) 
(JSONValue.parse(jsonString) ); 

JSONArray array02 = (JSONArray ) 
(jJson0bj05.get("person") ); 


JSONObject temp01 = (JSONObject ) 
(arrayO2.get(0)); 

String temp02 = temp01.get("Name"); 

System.out.println(temp02) ; 


}//end main 


}//end class Code01 


Note: 
Listing 2 


Te Ie Re Resets aes aa Yarns Mea aoe GN Ca ae See Ne gee Pattee cence es oe a 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


KRKEKEKRKKKKRKRKRKRKREKEKRKEKEKRKRE KERR KR KEK KRKEKEKE KEK RR KEKE KEK KEKE KKK KRKEKEKEKEKEEKESE 


Re Ae eta Rae ne eee iat ne nn 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONValue; 


Class Code02{ 


public static void main(String[] args){ 
JSONObject jsonObj01 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray arrayO1 = new JSONArray(); 
arrayO1.add(jsonObj01); 
arrayO1.add(jsonObj02); 
array0O1.add(json0bj03); 


JSONObject json0Obj04 = new JSONObject(); 
json0bj04.put("person",array01); 


String jsonString = jsonObj04.toJSONString(); 


JSONObject jsonObj05 = (JSONObject) 
(JSONValue.parse(jsonString) ); 

JSONArray array02 = (JSONArray) 
(jsonObj05.get("person") ); 


JSONObject tempO01 = (JSONObject) 
(arrayO2.get(0)); 

String temp02 = (String)(temp01.get("Name")); 

System.out.println(temp02) ; 


JSONObject tempO03 = (JSONObject ) 
(arrayO2.get(1)); 

Long temp04 = (String)(temp03.get("Age")); 

System.out.println(temp04) ; 


}//end main 


}//end class Code02 


Note: 
Listing 3 


TOR RR LG REIL ROAR RN OR Masa te cae ae te aN tea Waid aman ae eee IM a te Micah, Oe 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


KRKEKEKKRKKKRKRKRKRKREKRKEKRKEKRKR KERR KE KERR RE KEK KERR KE KKK KEKE KRKRKKEKEKEEKESE 


eh argh PRR, ROR om A ae 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONValue; 


Class Code03{ 


public static void main(String[] args){ 
JSONObject jsonObjO1 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray arrayO1 = new JSONArray(); 
array0O1.add(jsonObj01); 
arrayO1.add(jsonObj02); 
array01.add(json0bj03); 


JSONObject jsonObj04 = new JSONObject(); 
json0bj04.put("person",array01); 


String jsonString = json0Obj04.toJSONString(); 


JSONObject jsonObj05 = (JSONObject) 
(JSONValue.parse(jsonString) ); 

JSONArray array02 = (JSONArray ) 
(json0Obj05.get("person") ); 


JSONObject tempO01 = (JSONObject ) 
(arrayO2.get(0)); 

String temp02 = (String)(temp01.get("Name") ); 

System.out.println(temp02) ; 


JSONObject tempO03 = (JSONObject ) 
(arrayO2.get(1)); 

Long temp04 = (Long)(temp03.get("Age")); 

System.out.printiln(temp04) ; 


JSONObject temp05 = (JSONObject ) 
(arrayO02.get(2)); 

Boolean temp06 = (String) 
(temp05.get("Student")); 

System.out.println(temp06) ; 


}//end main 


}//end class Code03 


Note: 
Listing 4 


eo ive PPR cathe Marea ea tuiatee yen ea pon Nea aie tous Jena ars Nore args ite aot a SN ia ae 


Copyright: R.G.Baldwin 2016 


Tested with Java 8, Windows 7, and 
json-simple-1.1.1. 


KKEKKKKKEKKRKRKREKR KEK KRKR KEKE KEKE KRKRKR KEKE KERR KEKE KEK KK KEKE KEKE KERR KKK KKEKEEKSE 


PWD ea aah Ica ee. etree ma are 74 


import org.json.simple.JSONObject; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONValue; 


Class Code04{ 


public static void main(String[] args) { 
JSONObject jsonObjO1 = new JSONObject(); 
json0bj01.put( "Name", "Tom" ); 
JSONObject jsonObj02 = new JSONObject(); 
json0bj02.put("Age", 21); 
JSONObject jsonObj03 = new JSONObject(); 
json0bj03.put( "Student", true); 


JSONArray arrayO1 = new JSONArray(); 
arrayO1.add(jsonObj01); 
arrayO1.add(json0Obj02); 
arrayO1.add(json0Obj03); 


JSONObject jsonObj04 = new JSONObject(); 
json0bj04.put("person",array01); 


String jsonString = json0Obj04.toJSONString(); 


JSONObject jsonObj05 = (JSONObject) 
(JSONValue.parse(jsonString) ); 

JSONArray array02 = (JSONArray) 
(json0Obj05.get("person") ); 


JSONObject temp01 = (JSONObject ) 
(arrayO2.get(0)); 

String temp02 = (String)(temp01.get("Name")); 

System.out.println(temp02) ; 


JSONObject temp03 = (JSONObject ) 
(arrayO2.get(1)); 

Long temp04 = (Long)(temp03.get("Age")); 

System.out.println(temp04) ; 


JSONObject temp05 = (JSONObject ) 
(arrayO2.get(2)); 
Boolean temp06 = (Boolean) 


(temp05.get("Student") ); 
System.out.println(temp06) ; 


}//end main 


}//end class Code04 


Miscellaneous 


This section contains a variety of miscellaneous information. 


Note: Housekeeping material 


e Module name: Json0230R: Review 
e File: Json0230R.htm 
e Published: 06/07/16 


Note: Disclaimers: 

Financial : Although the Connexions site makes it possible for you to 
download a PDF file for this module at no charge, and also makes it 
possible for you to purchase a pre-printed version of the PDF file, you 
should be aware that some of the HTML elements in this module may not 
translate well into PDF. 

I also want you to know that, I receive no financial compensation from the 
Connexions website even if you purchase the PDF version of the module. 
In the past, unknown individuals have copied my modules from cnx.org, 
converted them to Kindle books, and placed them for sale on Amazon.com 
showing me as the author. I neither receive compensation for those sales 
nor do I know who does receive compensation. If you purchase such a 
book, please be aware that it is a copy of a module that is freely available 
on cnx.org and that it was made and published without my prior 
knowledge. 

Affiliation : I am a professor of Computer Information Technology at 
Austin Community College in Austin, TX. 


-end- 


Java4710: INEW 2338 - Java EE 7 and Frameworks 

This is the cover page for links to PDF files on Java EE 7 Frameworks that 
are part of the course named INEW 2338, Advanced Java at Austin 
Community College in Austin, TX. 


Table of Contents 


e Preface 
e Links to Chapters 
e Miscellaneous 


Preface 


e This is the main page for links to content on Java EE 7 and 
Frameworks that are part of the course named INEW 2338, Advanced 
Java at Austin Community College in Austin, TX. 

e The material in the chapters is sequential and is designed for 
progressive study. Most chapters contain material that references 
concepts and code in prior chapters. 

e Assignments and the section exam are located in Blackboard. 


Links to Chapters 


01 - JDK-WildFly-NetBeans Setup Local 


02 - WildFly Setup Remote 


03 - First Servlet 
04 - JSF Tags 
05 - JSF Template Demo 


06 - PrimeFaces Component Suite 


07a - MySQL Installer 


07b - XAMPP Setup 


08 - Database Setup 


11 - JSF and JOBC 
12 - JSF-MVC and Spring-MVC 


13 - Glossary 


Miscellaneous 


Due to the dynamic nature of the material, the content at the links above is 
periodically updated and the links themselves may change. While you are 
welcome to print the pages, I recommend bookmarking this main page for 
future reference. Since the links may change, by bookmarking this main 
page, you will have access to the current content and working links. 


I hope you enjoy the course. 


@author R.L. Martinez, Ph.D.